0

我想阅读下面的 XML 格式,只需要一些属性而不是全部。例如:

<Parts>
-   <Part>
        <Section>3003512</Section> 
        <Mark>RP-103</Mark> 
        <Length>4950</Length> 
        - <Components>
                <Section>3003512</Section> 
                <Mark>RP-103</Mark> 
                <Length>4950</Length>
                <Remark>System Generated </Remark>
              <Components />
            <Remark>No Comments </Remark>
        </Part>

-   <Part>
        <Section>3003512</Section> 
        <Mark>RP-103</Mark> 
        <Length>4950</Length> 
        <Components />
        <Remark>No Comments </Remark>
     </Part>
</Parts>

我想只读部分并以表格格式标记。我正在使用下面的代码来阅读这个但是它给出了错误表架构'组件'已经存在。

        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Mark");
        DataColumn dc1 = new DataColumn("Sections ");
        dt.Columns.Add(dc); 
        dt.Columns.Add(dc1);
        DataSet dSet = new DataSet();


        if (File.Exists(xmlpath2))
        {

            XmlTextReader Reader1 = new XmlTextReader(xmlpath2);



            dSet.ReadXml(Reader1, XmlReadMode.Auto);


            for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
            {
                DataRow rows = dSet.Tables[0].Rows[i];
                DataRow myRow = dt.NewRow();
                myRow["Mark"] = rows["Mark"];
                myRow["Sections "] = rows["Sections "];

                dt.Rows.Add(myRow);
            }


            GridView1.DataSource = dt;
            GridView1.DataBind(); 

        }
4

2 回答 2

0

不久前正在做类似的事情: LINQ multiple columns

希望能让你走上正轨

于 2012-05-17T03:53:26.023 回答
0

这是一个使用LINQ to XML的示例:

var ele = XElement.Parse(xml); // change to XElement.Load if loading from file

var result = ele.Descendants("Section")
                .Zip(ele.Descendants("Mark"), 
                    (s,m) => new {Section = s.Value, Mark = m.Value});

现在您可以创建您的DataTable

var table = new DataTable();
var marks = new DataColumn("Mark");
var sections = new DataColumn("Sections");

table.Columns.Add(marks);
table.Columns.Add(sections);

foreach (var item in result)
{
    var row = table.NewRow();
    row["Mark"] = item.Mark;
    row["Sections"] = item.Section;
    table.Rows.Add(row);
}

这将产生:

Mark     Sections 
RP-103   3003512 
RP-103   3003512 
RP-103   3003512 

它假定每个Section后面都有一个对应的Mark. 它还需要System.Xml.LinqSystem.Linq

于 2012-05-17T03:59:07.093 回答