是否可能以相同的字段方向循环元素。
<?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文件。请参考下面的需求输出:
ppsitecode ppsitedesc ppqty ppunit
0062 AAAAAAA 1.00 C24
0269 BBBBBBB 1.00 C24
2546 CCCCCCC 1.00 C24
答案 0 :(得分:0)
使用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;
}
}
}
}