使用C#或Java读取XML文档

时间:2012-05-17 03:47:24

标签: c# java xml xml-parsing

我想阅读下面的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(); 

        }

2 个答案:

答案 0 :(得分:0)

一段时间做了类似的事情: LINQ multiple columns

希望能让你走上正轨

答案 1 :(得分: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