C# XML使用c加载重复的元素#
是否可以使用相同方向的字段循环元素C# XML使用c加载重复的元素#,c#,xml,xmldocument,C#,Xml,Xmldocument,是否可以使用相同方向的字段循环元素 <?xml version="1.0" encoding="utf-8"?> <xml> <document> <sls> <ppsitecode>0062</ppsitecode>
<?xml version="1.0" encoding="utf-8"?>
<xml>
<document>
<sls>
<ppsitecode>0062</ppsitecode>
<ppsitedesc><![CDATA[AAAAAAA]]></ppsitedesc>
<ppqty>1.00</ppqty>
<ppunit>C24</ppunit>
<ppsitecode>0269</ppsitecode>
<ppsitedesc><![CDATA[BBBBBBB]]></ppsitedesc>
<ppqty>1.00</ppqty>
<ppunit>C24</ppunit>
<ppsitecode>2546</ppsitecode>
<ppsitedesc><![CDATA[CCCCCCC]]></ppsitedesc>
<ppqty>1.00</ppqty>
<ppunit>C24</ppunit>
</sls>
</document>
</xml>
使用xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication83
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement sls = doc.Descendants("sls").FirstOrDefault();
DataTable dt = new DataTable();
string[] columns = sls.Elements().Select(x => x.Name.LocalName).Distinct().ToArray();
foreach (string column in columns)
{
dt.Columns.Add(column, typeof(string));
}
DataRow newRow = null;
foreach (XElement element in sls.Elements())
{
string columnName = element.Name.LocalName;
if (columnName == "ppsitecode") newRow = dt.Rows.Add();
newRow[columnName] = (string)element;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication83
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement sls = doc.Descendants("sls").FirstOrDefault();
DataTable dt = new DataTable();
string[] columns = sls.Elements().Select(x => x.Name.LocalName).Distinct().ToArray();
foreach (string column in columns)
{
dt.Columns.Add(column, typeof(string));
}
DataRow newRow = null;
foreach (XElement element in sls.Elements())
{
string columnName = element.Name.LocalName;
if (columnName == "ppsitecode") newRow = dt.Rows.Add();
newRow[columnName] = (string)element;
}
}
}
}