I have an xml like this:
5
7
9
Try the following code:
public DataTable GetColumnsFromXML(String XMLPath, String TableName)
{
DataTable dtForColumns = DatatableforColumns();
XmlDataDocument xmldoc = new XmlDataDocument();
xmldoc.Load(XMLPath);
XmlElement root = xmldoc.DocumentElement;
XmlNodeList tablenodes = root.SelectNodes("Table");
if (tablenodes != null)
foreach (XmlNode nodes in tablenodes)
{
if (!nodes.HasChildNodes) continue;
if (nodes.Attributes == null) continue;
//TableName = nodes.Attributes[0].Value;
if (nodes.Attributes[0].Value == TableName)
{
String PrimaryKey = nodes.Attributes[1].Value;
var nodesdisplayname = nodes.SelectNodes("Column/DisplayColumn");
var nodesorignalvalue = nodes.SelectNodes("Column/OrignalColumn");
if (nodesdisplayname != null && nodesorignalvalue != null)
{
for (int i = 0; i <= nodesdisplayname.Count - 1; i++)
{
var xmlDisplayNode = nodesdisplayname.Item(i);
var xmlOrignalNode = nodesorignalvalue.Item(i);
if (xmlDisplayNode != null && xmlOrignalNode != null)
{
DataRow dr;
dr = dtForColumns.NewRow();
dr["DisplayColumn"] = xmlDisplayNode.InnerText;
dr["OrignalColumn"] = xmlOrignalNode.InnerText;
dr["PrimaryKey"] = PrimaryKey;
dtForColumns.Rows.Add(dr);
}
}
}
}
}
return dtForColumns;
}
private DataTable DatatableforColumns()
{
DataTable dt = new DataTable();
dt.Columns.Add("DisplayColumn", typeof(String));
dt.Columns.Add("OrignalColumn", typeof(String));
dt.Columns.Add("PrimaryKey", typeof(String));
return dt;
}
To Access these here is the code:
DataTable dtColumns = new DataTable();
dtColumns = objXML.GetColumnsFromXML(Server.MapPath("~/XMLFile.xml"), TableName);
Customize it according to your requirement, hope this will work for you.
I don't know it is fast enough for you but I'll give it a try
string s = String.Join("," , xDoc.Descendants("PersonID").Select(p => (string)p));
You can use LINQ to XML with string.Join like:
XDocument xmlDoc = XDocument.Parse(@"<People>
<PersonID>5</PersonID>
<PersonID>7</PersonID>
<PersonID>9</PersonID>
</People>");
var val = xmlDoc.Descendants("People")
.SelectMany(r => r.Elements("PersonID"))
.Select(r => r.Value);
string str = string.Join(",", val);
str
will be str = "5,7,9"