2017-08-14 145 views
0

尝试从第二行获取数据。 在这第二行我需要阅读: - col subrows - 行。Linq XML属性读取元素

它非常困惑一个我的代码我得到的所有的行... 请帮助如何去it..I无法弄清楚如何与复杂的XML文档

C#

 path = path + "/PongraweDriver.xml"; 
     XElement root = XElement.Load(path); 

     IEnumerable<XElement> datasource = 
      from el in root.Descendants("table") 
      where (string)el.Attribute("name") == "Eco driving" 
      select el; 

     IEnumerable<XElement> rowdata = 
      from elm in datasource.Descendants("row") 
      //where (string)el.Attribute("name") == "Eco driving" 
      select elm; 

     foreach (XElement elm in rowdata) 
      Console.WriteLine(elm); 
工作

XML

 <table cols="3" flags="16781440" id="drivers_group_ecodriving" 
     name="Eco driving" rows="3"> 
     <header> 
      <col name="№"/> 
      <col name="Grouping"/> 
      <col name="Count"/> 
     </header> 
     <row> 
      <col txt="1" val="0" vt="0"/> 
      <col txt="Kyaw Min Oo" val="0" vt="0"/> 
      <col txt="5" val="5" vt="2"/> 
      <subrows> 
       <row> 
        <col txt="1.1" val="0" vt="0"/> 
        <col txt="Harsh Brake Km/h.s" val="0" vt="0"/> 
        <col txt="2" val="2" vt="2"/> 
       </row> 
       <row> 
        <col txt="1.2" val="0" vt="0"/> 
        <col txt="OverSpeed-Medium" val="0" vt="0"/> 
        <col txt="3" val="3" vt="2"/> 
       </row> 
      </subrows> 
     </row> 
    </table> 

回答

0

我使用了XML LINQ在C#中把结果转换成一个数据表。看到下面的代码

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 
using System.Data; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 

      XElement table = doc.Descendants("table").FirstOrDefault(); 

      DataTable dt = new DataTable((string)table.Attribute("name")); 

      XElement header = table.Element("header"); 
      foreach (XElement col in header.Elements("col")) 
      { 
       dt.Columns.Add((string)col.Attribute("name"), typeof(string)); 
      } 
      foreach (XElement row in table.Descendants("row")) 
      { 
       string[] rowData = row.Elements("col").Select(x => (string)x.Attribute("txt")).ToArray(); 
       dt.Rows.Add(rowData); 
      } 
     } 
    } 
} 
+0

你的天才..只是我需要..抱歉打扰你。但我将如何选择具有属性的表格。现在你已经使用firstOrDfault。我如何告诉它使用属性náme'= eco –

+0

来加载表格,因为只需要一个表格,所以在使用Descendants/Elements时我不得不使用firstOrDefault。 doc.Descendants(“table”)。其中(x =>(string)x.Attribute(“name”)==“eco - nadeem”)。FirstOrDefault(); – jdweng