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>
13 // (c)copyright 2002 Ville Palo
15 // XmlDataLoader is included within the Mono Class Library.
21 using System.Xml.XPath;
22 using System.Collections;
23 using System.Globalization;
28 internal class XmlDataLoader
32 Hashtable DiffGrRows = new Hashtable ();
34 public XmlDataLoader (DataSet set)
39 public XmlReadMode LoadData (XmlReader reader, XmlReadMode mode)
41 XmlReadMode Result = XmlReadMode.Auto;
45 case XmlReadMode.Fragment:
47 case XmlReadMode.ReadSchema:
48 case XmlReadMode.IgnoreSchema:
49 case XmlReadMode.InferSchema:
51 ReadModeSchema (reader, mode);
62 // Read information from the reader.
63 private void ReadModeSchema (XmlReader reader, XmlReadMode mode)
65 bool inferSchema = mode == XmlReadMode.InferSchema ? true : false;
66 //check if the current element is schema.
67 if (String.Compare (reader.LocalName, "schema", true) == 0) {
69 if (mode == XmlReadMode.InferSchema || mode == XmlReadMode.IgnoreSchema)
70 reader.Skip(); // skip the schema node.
72 DSet.ReadXmlSchema(reader);
74 reader.MoveToContent();
76 // load an XmlDocument from the reader.
77 XmlDocument doc = BuildXmlDocument(reader);
79 // treatment for .net compliancy :
80 // if xml representing dataset has exactly depth of 2 elements,
81 // than the root element actually represents datatable and not dataset
82 // so we add new root element to doc
83 // in order to create an element representing dataset.
84 int rootNodeDepth = XmlNodeElementsDepth(doc.DocumentElement);
85 if (rootNodeDepth == 2) {
87 String newDataSetName = "NewDataSet";
88 // create new document
89 XmlDocument newDoc = new XmlDocument();
90 // create element for dataset
91 XmlElement datasetElement = newDoc.CreateElement(newDataSetName);
92 // make the new created element to be the new doc root
93 newDoc.AppendChild(datasetElement);
94 // import all the elements from doc and insert them into new doc
95 XmlNode root = newDoc.ImportNode(doc.DocumentElement,true);
96 datasetElement.AppendChild(root);
98 // update dataset name
99 DSet.DataSetName = newDataSetName;
102 // set EnforceConstraint to false - we do not want any validation during
104 bool origEnforceConstraint = DSet.EnforceConstraints;
105 DSet.EnforceConstraints = false;
107 // The childs are tables.
108 XmlNodeList nList = doc.DocumentElement.ChildNodes;
110 for (int i = 0; i < nList.Count; i++) {
111 XmlNode node = nList[i];
112 // node represents a table onky if it is of type XmlNodeType.Element
113 if (node.NodeType == XmlNodeType.Element) {
114 AddRowToTable(node, null, inferSchema);
118 // set the EnforceConstraints to original value;
119 DSet.EnforceConstraints = origEnforceConstraint;
122 #endregion // reading
124 #region Private helper methods
126 private void ReadColumns (XmlReader reader, DataRow row, DataTable table, string TableName)
129 if (reader.NodeType == XmlNodeType.Element) {
130 DataColumn col = table.Columns [reader.LocalName];
132 row [col] = StringToObject (col.DataType, reader.Value);
140 } while (table.TableName != reader.LocalName
141 || reader.NodeType != XmlNodeType.EndElement);
144 internal static object StringToObject (Type type, string value)
146 if (type == null) return value;
148 switch (Type.GetTypeCode (type)) {
149 case TypeCode.Boolean: return XmlConvert.ToBoolean (value);
150 case TypeCode.Byte: return XmlConvert.ToByte (value);
151 case TypeCode.Char: return (char)XmlConvert.ToInt32 (value);
152 case TypeCode.DateTime: return XmlConvert.ToDateTime (value);
153 case TypeCode.Decimal: return XmlConvert.ToDecimal (value);
154 case TypeCode.Double: return XmlConvert.ToDouble (value);
155 case TypeCode.Int16: return XmlConvert.ToInt16 (value);
156 case TypeCode.Int32: return XmlConvert.ToInt32 (value);
157 case TypeCode.Int64: return XmlConvert.ToInt64 (value);
158 case TypeCode.SByte: return XmlConvert.ToSByte (value);
159 case TypeCode.Single: return XmlConvert.ToSingle (value);
160 case TypeCode.UInt16: return XmlConvert.ToUInt16 (value);
161 case TypeCode.UInt32: return XmlConvert.ToUInt32 (value);
162 case TypeCode.UInt64: return XmlConvert.ToUInt64 (value);
165 if (type == typeof (TimeSpan)) return XmlConvert.ToTimeSpan (value);
166 if (type == typeof (byte[])) return Convert.FromBase64String (value);
168 return Convert.ChangeType (value, type);
171 private void AddRowToTable(XmlNode tableNode, DataColumn relationColumn, bool inferSchema)
173 Hashtable rowValue = new Hashtable();
176 // Check if the table exists in the DataSet. If not create one.
177 if (DSet.Tables.Contains(tableNode.LocalName))
178 table = DSet.Tables[tableNode.LocalName];
179 else if (inferSchema) {
180 table = new DataTable(tableNode.LocalName);
181 DSet.Tables.Add(table);
186 // For elements that are inferred as tables and that contain text
187 // but have no child elements, a new column named "TableName_Text"
188 // is created for the text of each of the elements.
189 // If an element is inferred as a table and has text, but also has child elements,
190 // the text is ignored.
191 // Note : if an element is inferred as a table and has text
192 // and has no child elements,
193 // but the repeated ements of this table have child elements,
194 // then the text is ignored.
195 if(!HaveChildElements(tableNode) && HaveText(tableNode) &&
196 !IsRepeatedHaveChildNodes(tableNode)) {
197 string columnName = tableNode.Name + "_Text";
198 if (!table.Columns.Contains(columnName)) {
199 table.Columns.Add(columnName);
201 rowValue.Add(columnName, tableNode.InnerText);
204 // Get the child nodes of the table. Any child can be one of the following tow:
205 // 1. DataTable - if there was a relation with another table..
206 // 2. DataColumn - column of the current table.
207 XmlNodeList childList = tableNode.ChildNodes;
208 for (int i = 0; i < childList.Count; i++) {
209 XmlNode childNode = childList[i];
211 // we are looping through elements only
212 // Note : if an element is inferred as a table and has text, but also has child elements,
213 // the text is ignored.
214 if (childNode.NodeType != XmlNodeType.Element)
217 // Elements that have attributes are inferred as tables.
218 // Elements that have child elements are inferred as tables.
219 // Elements that repeat are inferred as a single table.
220 if (IsInferedAsTable(childNode)) {
221 // child node infered as table
223 // We need to create new column for the relation between the current
224 // table and the new table we found (the child table).
225 string newRelationColumnName = table.TableName + "_Id";
226 if (!table.Columns.Contains(newRelationColumnName)) {
227 DataColumn newRelationColumn = new DataColumn(newRelationColumnName, typeof(int));
228 newRelationColumn.AutoIncrement = true;
229 // we do not want to serialize this column so MappingType is Hidden.
230 newRelationColumn.ColumnMapping = MappingType.Hidden;
231 table.Columns.Add(newRelationColumn);
233 // Add a row to the new table we found.
234 AddRowToTable(childNode, table.Columns[newRelationColumnName], inferSchema);
237 AddRowToTable(childNode, null, inferSchema);
241 // Elements that have no attributes or child elements, and do not repeat,
242 // are inferred as columns.
244 if (childNode.FirstChild != null)
245 val = childNode.FirstChild.Value;
248 if (table.Columns.Contains(childNode.LocalName))
249 rowValue.Add(childNode.LocalName, val);
250 else if (inferSchema) {
251 table.Columns.Add(childNode.LocalName);
252 rowValue.Add(childNode.LocalName, val);
258 // Column can be attribute of the table element.
259 XmlAttributeCollection aCollection = tableNode.Attributes;
260 for (int i = 0; i < aCollection.Count; i++) {
261 XmlAttribute attr = aCollection[i];
262 //the atrribute can be the namespace.
263 if (attr.Prefix.Equals("xmlns"))
264 table.Namespace = attr.Value;
265 else { // the attribute is a column.
266 if (!table.Columns.Contains(attr.LocalName))
267 table.Columns.Add(attr.LocalName);
268 table.Columns[attr.LocalName].Namespace = table.Namespace;
270 rowValue.Add(attr.LocalName, attr.Value);
274 // If the current table is a child table we need to add a new column for the relation
275 // and add a new relation to the DataSet.
276 if (relationColumn != null) {
277 if (!table.Columns.Contains(relationColumn.ColumnName)) {
278 DataColumn dc = new DataColumn(relationColumn.ColumnName, typeof(int));
279 // we do not want to serialize this column so MappingType is Hidden.
280 dc.ColumnMapping = MappingType.Hidden;
281 table.Columns.Add(dc);
282 // Convention of relation name is: ParentTableName_ChildTableName
283 DataRelation dr = new DataRelation(relationColumn.Table.TableName + "_" + dc.Table.TableName, relationColumn, dc);
285 DSet.Relations.Add(dr);
287 rowValue.Add (relationColumn.ColumnName, relationColumn.GetAutoIncrementValue());
290 // Create new row and add all values to the row.
291 // then add it to the table.
292 DataRow row = table.NewRow ();
294 IDictionaryEnumerator enumerator = rowValue.GetEnumerator ();
295 while (enumerator.MoveNext ()) {
296 row [enumerator.Key.ToString ()] = StringToObject (table.Columns[enumerator.Key.ToString ()].DataType, enumerator.Value.ToString ());
299 table.Rows.Add (row);
303 // bulid the document from the reader.
304 private XmlDocument BuildXmlDocument(XmlReader reader)
306 XmlDocument doc = new XmlDocument();
307 // Create the root element. This is the DataSet element.
308 XmlElement dataSetElement = doc.CreateElement(DSet.DataSetName);
311 XmlNode n = doc.ReadNode (reader);
313 // Add the table nodes to the DataSet node.
314 dataSetElement.AppendChild (n);
315 } while (reader.IsStartElement());
317 // Add the DataSet element to the document.
318 doc.AppendChild(dataSetElement);
322 // this method calculates the depth of child nodes tree
323 // and it counts nodes of type XmlNodeType.Element only
324 private static int XmlNodeElementsDepth(XmlNode node)
327 if ((node != null)) {
328 if ((node.HasChildNodes) && (node.FirstChild.NodeType == XmlNodeType.Element)) {
329 for (int i=0; i<node.ChildNodes.Count; i++) {
330 if (node.ChildNodes[i].NodeType == XmlNodeType.Element) {
331 int childDepth = XmlNodeElementsDepth(node.ChildNodes[i]);
332 maxDepth = (maxDepth < childDepth) ? childDepth : maxDepth;
344 return (maxDepth + 1);
347 private bool HaveChildElements(XmlNode node)
349 bool haveChildElements = true;
350 if(node.ChildNodes.Count > 0) {
351 foreach(XmlNode childNode in node.ChildNodes) {
352 if (childNode.NodeType != XmlNodeType.Element) {
353 haveChildElements = false;
359 haveChildElements = false;
361 return haveChildElements;
364 private bool HaveText(XmlNode node)
366 bool haveText = true;
367 if(node.ChildNodes.Count > 0) {
368 foreach(XmlNode childNode in node.ChildNodes) {
369 if (childNode.NodeType != XmlNodeType.Text) {
381 private bool IsRepeat(XmlNode node)
383 bool isRepeat = false;
384 if(node.ParentNode != null) {
385 foreach(XmlNode childNode in node.ParentNode.ChildNodes) {
386 if(childNode != node && childNode.Name == node.Name) {
395 private bool HaveAttributes(XmlNode node)
397 return (node.Attributes != null && node.Attributes.Count > 0);
400 private bool IsInferedAsTable(XmlNode node)
402 // Elements that have attributes are inferred as tables.
403 // Elements that have child elements are inferred as tables.
404 // Elements that repeat are inferred as a single table.
405 return (HaveChildElements(node) || HaveAttributes(node) ||
410 /// Returns true is any node that is repeated node for the node supplied
411 /// (i.e. is child node of node's parent, have the same name and is not the node itself)
412 /// have child elements
414 private bool IsRepeatedHaveChildNodes(XmlNode node)
416 bool isRepeatedHaveChildElements = false;
417 if(node.ParentNode != null) {
418 foreach(XmlNode childNode in node.ParentNode.ChildNodes) {
419 if(childNode != node && childNode.Name == node.Name) {
420 if (HaveChildElements(childNode)) {
421 isRepeatedHaveChildElements = true;
427 return isRepeatedHaveChildElements;
430 #endregion // Private helper methods