CSharp examples for System.Xml:XML Node
Converts a list of Xml nodes to a DataTable and sets one of the columns as a primary key.
// All rights reserved. using System.Diagnostics; using System.Collections.Specialized; using System.Xml; using System.Data; using System;/*ww w . j av a 2s . c om*/ public class Main{ /// <summary> /// Converts a list of Xml nodes to a DataTable and sets one of the columns as a primary key. /// </summary> /// <param name="nodelist"></param> /// <param name="primaryKey"></param> /// <returns></returns> public static DataTable GetDataTable(XmlNodeList nodelist, string primaryKeyColumn, bool autoIncrement) { DataTable table = null; XmlNode node = null; if (nodelist == null) return null; // get parameter names node = nodelist.Item(0); if (node == null) return null; XmlAttributeCollection attrCollection = node.Attributes; if (attrCollection == null) return null; if (attrCollection.Count == 0) return null; // create data table table = new DataTable(); bool primaryKeyFieldFound = false; foreach (XmlAttribute attr in attrCollection) { if (attr.Name == primaryKeyColumn) primaryKeyFieldFound = true; table.Columns.Add(attr.Name); } if (!primaryKeyFieldFound) throw new Exception("Unable to set primary key in datatable because field '" + primaryKeyColumn + "'was not found."); table.PrimaryKey = new DataColumn[] { table.Columns[primaryKeyColumn] }; if (autoIncrement) { table.Columns[primaryKeyColumn].AutoIncrement = true; table.Columns[primaryKeyColumn].AutoIncrementStep = 1; } // add rows DataRow row = null; foreach (XmlNode n in nodelist) { row = table.NewRow(); foreach (XmlAttribute a in n.Attributes) { row[a.Name] = a.Value; } table.Rows.Add(row); } table.AcceptChanges(); return table; } #endregion #region Datatable Manipulation /// ----------------------------------------------------------------------------- /// <summary>s /// Converts a list of Xml nodes to a DataTable. /// </summary> /// <param name="nodelist">List of Xml nodes</param> /// <returns>DataTable</returns> /// <remarks> /// This method convert /// </remarks> /// ----------------------------------------------------------------------------- public static DataTable GetDataTable(XmlNodeList nodelist) { DataTable table = null; XmlNode node = null; if (nodelist == null) return null; // get parameter names node = nodelist.Item(0); if (node == null) return null; XmlAttributeCollection attrCollection = node.Attributes; if (attrCollection == null) return null; if (attrCollection.Count == 0) return null; // create data table table = new DataTable(); foreach (XmlAttribute attr in attrCollection) { table.Columns.Add(attr.Name); } // add rows DataRow row = null; foreach (XmlNode n in nodelist) { row = table.NewRow(); foreach (XmlAttribute a in n.Attributes) { row[a.Name] = a.Value; } table.Rows.Add(row); } table.AcceptChanges(); return table; } }