2 // mcs/class/System.Data/System.Data/XmlDataLoader.cs
4 // Purpose: Loads XmlDocument to DataSet
6 // class: XmlDataLoader
7 // assembly: System.Data.dll
8 // namespace: System.Data
11 // Ville Palo <vi64pa@koti.soon.fi>
12 // Atsushi Enomoto <atsushi@ximian.com>
14 // (c)copyright 2002 Ville Palo
15 // (C)2004 Novell Inc.
17 // XmlDataLoader is included within the Mono Class Library.
21 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
23 // Permission is hereby granted, free of charge, to any person obtaining
24 // a copy of this software and associated documentation files (the
25 // "Software"), to deal in the Software without restriction, including
26 // without limitation the rights to use, copy, modify, merge, publish,
27 // distribute, sublicense, and/or sell copies of the Software, and to
28 // permit persons to whom the Software is furnished to do so, subject to
29 // the following conditions:
31 // The above copyright notice and this permission notice shall be
32 // included in all copies or substantial portions of the Software.
34 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
35 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
37 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
38 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
39 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
40 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
46 using System.Collections;
47 using System.Globalization;
52 internal class XmlDataLoader
57 public XmlDataLoader (DataSet set)
62 public XmlReadMode LoadData (XmlReader reader, XmlReadMode mode)
64 XmlReadMode Result = mode;
67 case XmlReadMode.Auto:
68 Result = DSet.Tables.Count == 0 ? XmlReadMode.InferSchema : XmlReadMode.IgnoreSchema;
69 ReadModeSchema (reader, DSet.Tables.Count == 0 ? XmlReadMode.Auto : XmlReadMode.IgnoreSchema);
71 case XmlReadMode.InferSchema:
72 Result = XmlReadMode.InferSchema;
73 ReadModeSchema (reader, mode);
75 case XmlReadMode.IgnoreSchema:
76 Result = XmlReadMode.IgnoreSchema;
77 ReadModeSchema (reader, mode);
89 // Read information from the reader.
90 private void ReadModeSchema (XmlReader reader, XmlReadMode mode)
92 bool inferSchema = mode == XmlReadMode.InferSchema || mode == XmlReadMode.Auto;
93 bool fillRows = mode != XmlReadMode.InferSchema;
94 // This check is required for full DiffGram.
95 // It is not described in MSDN and it is impossible
96 // with WriteXml(), but when writing XML using
97 // XmlSerializer, the output is like this:
99 // <schema>...</schema>
100 // <diffgram>...</diffgram>
103 // FIXME: This, this check should (also) be done
104 // after reading the top-level element.
106 //check if the current element is schema.
107 if (reader.LocalName == "schema") {
108 if (mode != XmlReadMode.Auto)
109 reader.Skip(); // skip the schema node.
111 DSet.ReadXmlSchema(reader);
113 reader.MoveToContent();
116 // load an XmlDocument from the reader.
117 XmlDocument doc = new XmlDocument ();
119 if (doc.DocumentElement == null)
122 // treatment for .net compliancy :
123 // if xml representing dataset has exactly depth of 2 elements,
124 // than the root element actually represents datatable and not dataset
125 // so we add new root element to doc
126 // in order to create an element representing dataset.
128 // FIXME: Consider attributes.
129 // <root a='1' b='2' /> is regarded as a valid DataTable.
130 int rootNodeDepth = XmlNodeElementsDepth(doc.DocumentElement);
131 switch (rootNodeDepth) {
134 DSet.DataSetName = doc.DocumentElement.LocalName;
135 DSet.Prefix = doc.DocumentElement.Prefix;
136 DSet.Namespace = doc.DocumentElement.NamespaceURI;
140 // create new document
141 XmlDocument newDoc = new XmlDocument();
142 // create element for dataset
143 XmlElement datasetElement = newDoc.CreateElement("dummy");
144 // make the new created element to be the new doc root
145 newDoc.AppendChild(datasetElement);
146 // import all the elements from doc and insert them into new doc
147 XmlNode root = newDoc.ImportNode(doc.DocumentElement,true);
148 datasetElement.AppendChild(root);
153 DSet.DataSetName = doc.DocumentElement.LocalName;
154 DSet.Prefix = doc.DocumentElement.Prefix;
155 DSet.Namespace = doc.DocumentElement.NamespaceURI;
160 // set EnforceConstraint to false - we do not want any validation during
162 bool origEnforceConstraint = DSet.EnforceConstraints;
163 DSet.EnforceConstraints = false;
165 // The childs are tables.
166 XmlNodeList nList = doc.DocumentElement.ChildNodes;
168 // FIXME: When reading DataTable (not DataSet),
169 // the nodes are column items, not rows.
170 for (int i = 0; i < nList.Count; i++) {
171 XmlNode node = nList[i];
172 // node represents a table onky if it is of type XmlNodeType.Element
173 if (node.NodeType == XmlNodeType.Element) {
174 AddRowToTable(node, null, inferSchema, fillRows);
177 // set the EnforceConstraints to original value;
178 DSet.EnforceConstraints = origEnforceConstraint;
181 #endregion // reading
183 #region Private helper methods
185 private void ReadColumns (XmlReader reader, DataRow row, DataTable table, string TableName)
188 if (reader.NodeType == XmlNodeType.Element) {
189 DataColumn col = table.Columns [reader.LocalName];
191 row [col] = StringToObject (col.DataType, reader.Value);
199 } while (table.TableName != reader.LocalName
200 || reader.NodeType != XmlNodeType.EndElement);
203 internal static object StringToObject (Type type, string value)
205 if (type == null) return value;
207 switch (Type.GetTypeCode (type)) {
208 case TypeCode.Boolean: return XmlConvert.ToBoolean (value);
209 case TypeCode.Byte: return XmlConvert.ToByte (value);
210 case TypeCode.Char: return (char)XmlConvert.ToInt32 (value);
212 case TypeCode.DateTime: return XmlConvert.ToDateTime (value, XmlDateTimeSerializationMode.Unspecified);
214 case TypeCode.DateTime: return XmlConvert.ToDateTime (value);
216 case TypeCode.Decimal: return XmlConvert.ToDecimal (value);
217 case TypeCode.Double: return XmlConvert.ToDouble (value);
218 case TypeCode.Int16: return XmlConvert.ToInt16 (value);
219 case TypeCode.Int32: return XmlConvert.ToInt32 (value);
220 case TypeCode.Int64: return XmlConvert.ToInt64 (value);
221 case TypeCode.SByte: return XmlConvert.ToSByte (value);
222 case TypeCode.Single: return XmlConvert.ToSingle (value);
223 case TypeCode.UInt16: return XmlConvert.ToUInt16 (value);
224 case TypeCode.UInt32: return XmlConvert.ToUInt32 (value);
225 case TypeCode.UInt64: return XmlConvert.ToUInt64 (value);
228 if (type == typeof (TimeSpan)) return XmlConvert.ToTimeSpan (value);
229 if (type == typeof (Guid)) return XmlConvert.ToGuid (value);
230 if (type == typeof (byte[])) return Convert.FromBase64String (value);
231 if (type == typeof (System.Type)) return System.Type.GetType (value);
233 return Convert.ChangeType (value, type);
236 private void AddRowToTable(XmlNode tableNode, DataColumn relationColumn, bool inferSchema, bool fillRows)
238 Hashtable rowValue = new Hashtable();
241 // Check if the table exists in the DataSet. If not create one.
242 if (DSet.Tables.Contains(tableNode.LocalName))
243 table = DSet.Tables[tableNode.LocalName];
244 else if (inferSchema) {
245 table = new DataTable(tableNode.LocalName);
246 DSet.Tables.Add(table);
251 // For elements that are inferred as tables and that contain text
252 // but have no child elements, a new column named "TableName_Text"
253 // is created for the text of each of the elements.
254 // If an element is inferred as a table and has text, but also has child elements,
255 // the text is ignored.
256 // Note : if an element is inferred as a table and has text
257 // and has no child elements,
258 // but the repeated ements of this table have child elements,
259 // then the text is ignored.
260 if(!HaveChildElements(tableNode) && HaveText(tableNode) &&
261 !IsRepeatedHaveChildNodes(tableNode)) {
262 string columnName = tableNode.Name + "_Text";
263 if (!table.Columns.Contains(columnName)) {
264 table.Columns.Add(columnName);
266 rowValue.Add(columnName, tableNode.InnerText);
269 // Get the child nodes of the table. Any child can be one of the following tow:
270 // 1. DataTable - if there was a relation with another table..
271 // 2. DataColumn - column of the current table.
272 XmlNodeList childList = tableNode.ChildNodes;
273 for (int i = 0; i < childList.Count; i++) {
274 XmlNode childNode = childList[i];
276 // we are looping through elements only
277 // Note : if an element is inferred as a table and has text, but also has child elements,
278 // the text is ignored.
279 if (childNode.NodeType != XmlNodeType.Element)
282 // Elements that have attributes are inferred as tables.
283 // Elements that have child elements are inferred as tables.
284 // Elements that repeat are inferred as a single table.
285 if (IsInferredAsTable(childNode)) {
286 // child node inferred as table
288 // We need to create new column for the relation between the current
289 // table and the new table we found (the child table).
290 string newRelationColumnName = table.TableName + "_Id";
291 if (!table.Columns.Contains(newRelationColumnName)) {
292 DataColumn newRelationColumn = new DataColumn(newRelationColumnName, typeof(int));
293 newRelationColumn.AllowDBNull = false;
294 newRelationColumn.AutoIncrement = true;
295 // we do not want to serialize this column so MappingType is Hidden.
296 newRelationColumn.ColumnMapping = MappingType.Hidden;
297 table.Columns.Add(newRelationColumn);
299 // Add a row to the new table we found.
300 AddRowToTable(childNode, table.Columns[newRelationColumnName], inferSchema, fillRows);
303 AddRowToTable(childNode, null, inferSchema, fillRows);
307 // Elements that have no attributes or child elements, and do not repeat,
308 // are inferred as columns.
310 if (childNode.FirstChild != null)
311 val = childNode.FirstChild.Value;
314 if (table.Columns.Contains(childNode.LocalName))
315 rowValue.Add(childNode.LocalName, val);
316 else if (inferSchema) {
317 table.Columns.Add(childNode.LocalName);
318 rowValue.Add(childNode.LocalName, val);
324 // Column can be attribute of the table element.
325 XmlAttributeCollection aCollection = tableNode.Attributes;
326 for (int i = 0; i < aCollection.Count; i++) {
327 XmlAttribute attr = aCollection[i];
328 //the atrribute can be the namespace.
329 if (attr.Prefix.Equals("xmlns"))
330 table.Namespace = attr.Value;
331 else { // the attribute is a column.
332 if (!table.Columns.Contains(attr.LocalName)) {
333 DataColumn col = table.Columns.Add(attr.LocalName);
334 col.ColumnMapping = MappingType.Attribute;
336 table.Columns[attr.LocalName].Namespace = table.Namespace;
338 rowValue.Add(attr.LocalName, attr.Value);
342 // If the current table is a child table we need to add a new column for the relation
343 // and add a new relation to the DataSet.
344 if (relationColumn != null) {
345 if (!table.Columns.Contains(relationColumn.ColumnName)) {
346 DataColumn dc = new DataColumn(relationColumn.ColumnName, typeof(int));
347 // we do not want to serialize this column so MappingType is Hidden.
348 dc.ColumnMapping = MappingType.Hidden;
349 table.Columns.Add(dc);
350 // Convention of relation name is: ParentTableName_ChildTableName
351 DataRelation dr = new DataRelation(relationColumn.Table.TableName + "_" + dc.Table.TableName, relationColumn, dc);
353 DSet.Relations.Add(dr);
354 UniqueConstraint.SetAsPrimaryKey (dr.ParentTable.Constraints, dr.ParentKeyConstraint);
356 rowValue.Add (relationColumn.ColumnName, relationColumn.GetAutoIncrementValue());
359 // Create new row and add all values to the row.
360 // then add it to the table.
361 DataRow row = table.NewRow ();
363 IDictionaryEnumerator enumerator = rowValue.GetEnumerator ();
364 while (enumerator.MoveNext ()) {
365 row [enumerator.Key.ToString ()] = StringToObject (table.Columns[enumerator.Key.ToString ()].DataType, enumerator.Value.ToString ());
369 table.Rows.Add (row);
373 // this method calculates the depth of child nodes tree
374 // and it counts nodes of type XmlNodeType.Element only
375 private static int XmlNodeElementsDepth(XmlNode node)
378 if ((node != null)) {
379 if ((node.HasChildNodes) && (node.FirstChild.NodeType == XmlNodeType.Element)) {
380 for (int i=0; i<node.ChildNodes.Count; i++) {
381 if (node.ChildNodes[i].NodeType == XmlNodeType.Element) {
382 int childDepth = XmlNodeElementsDepth(node.ChildNodes[i]);
383 maxDepth = (maxDepth < childDepth) ? childDepth : maxDepth;
395 return (maxDepth + 1);
398 private bool HaveChildElements(XmlNode node)
400 bool haveChildElements = true;
401 if(node.ChildNodes.Count > 0) {
402 foreach(XmlNode childNode in node.ChildNodes) {
403 if (childNode.NodeType != XmlNodeType.Element) {
404 haveChildElements = false;
410 haveChildElements = false;
412 return haveChildElements;
415 private bool HaveText(XmlNode node)
417 bool haveText = true;
418 if(node.ChildNodes.Count > 0) {
419 foreach(XmlNode childNode in node.ChildNodes) {
420 if (childNode.NodeType != XmlNodeType.Text) {
432 private bool IsRepeat(XmlNode node)
434 bool isRepeat = false;
435 if(node.ParentNode != null) {
436 foreach(XmlNode childNode in node.ParentNode.ChildNodes) {
437 if(childNode != node && childNode.Name == node.Name) {
446 private bool HaveAttributes(XmlNode node)
448 return (node.Attributes != null && node.Attributes.Count > 0);
451 private bool IsInferredAsTable(XmlNode node)
453 // Elements that have attributes are inferred as tables.
454 // Elements that have child elements are inferred as tables.
455 // Elements that repeat are inferred as a single table.
456 return (HaveChildElements(node) || HaveAttributes(node) ||
461 /// Returns true is any node that is repeated node for the node supplied
462 /// (i.e. is child node of node's parent, have the same name and is not the node itself)
463 /// have child elements
465 private bool IsRepeatedHaveChildNodes(XmlNode node)
467 bool isRepeatedHaveChildElements = false;
468 if(node.ParentNode != null) {
469 foreach(XmlNode childNode in node.ParentNode.ChildNodes) {
470 if(childNode != node && childNode.Name == node.Name) {
471 if (HaveChildElements(childNode)) {
472 isRepeatedHaveChildElements = true;
478 return isRepeatedHaveChildElements;
481 #endregion // Private helper methods