2017-08-14 14 views
0

2行目からデータを取得しようとしています。 この2番目の行では、私は以下を読む必要があります: - col subrows - rows。属性付きLinq XML読み取り要素

そのは非常に私はすべての行を取得する私のコードで混乱... は複雑な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); 
と連携する方法を見つけ出すカントit..Iに取り掛かる方法を助けてください

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

私は、データテーブルに結果を置くためにC#での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 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 '=エコでテーブルをロードするように指示するのですか? –

+0

私はfirstOrDefaultを使う必要があった。 (x =>(文字列)x.Attribute( "name")== "eco-nadeem")FirstOrDefault(); doc.Descendants( "table")。 – jdweng

関連する問題