2012-05-17 45 views
0

我想在下面阅读XML格式只需要一些属性不是全部。 对于例如为:使用C#或Java读取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(); 

     } 
+0

有几个XML库可以帮助解决这个问题。尝试搜索更多,然后回来问。 – Riking

+3

让你介意--Java或C##,因为根据这个选择给出的答案会有很大的不同。 –

+0

什么是源中所有冗余的“空白”行。它是否应该让代码更快? –

回答

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

+0

代码工作正常。谢谢。请让我知道如何在下面的代码中绑定来自XML文档的三个值。 var result = ele.Descendants(“Section”) .Zip(ele.Descendants(“Mark”), (s,m)=> new {Section = s.Value,Mark = m.Value}); –

+0

@kuldeepverma我已经更新了答案,展示了如何创建'DataTable'。从这里没有更多的帮助。 – yamen

+0

谢谢你,我已经这样做了。但我无法绑定更多列。 进入数据表。 –