2016-02-19 55 views
-2

我在这个模板转换XML数据表

<tests> 
    <x> 
     <a></a> 
     <b></b> 
     <c></c> 
    </x> 
    <y> 
     <a></a> 
     <b></b> 
     <c></c> 
    </y> 
    <z> 
     <a></a> 
     <b></b> 
     <c></c> 
    </z> 
</tests> 

我只希望所有的东西里面<x>...</x>对等转换到数据表中的XML文件。

我该怎么做?

+5

您需要告诉我们您已经尝试了什么,或者您已经搜索过哪些内容才能引导您达成目标。 – TankorSmash

回答

0

这是一个办法:

public DataTable CreateDataTable(string fileName) 
{ 
    XElement xml = XElement.Load(fileName); 

    var tempRows = from x in xml.Descendants("x")      
        select new 
        { 
         A = (string)x.Element("a"), 
         B = (string)x.Element("b"), 
         C = (string)x.Element("c") 
        }; 

    DataTable dt = new DataTable(); 
    dt.Columns.Add("a", typeof(string)); 
    dt.Columns.Add("b", typeof(string)); 
    dt.Columns.Add("c", typeof(string));    

    foreach (var tempRow in tempRows) 
    { 
     dt.Rows.Add(tempRow.A, tempRow.B, tempRow.C); 
    } 

    return dt; 
} 
+0

谢谢! 但如果我的XML寻找的东西是这样的: ' ' –

0