2017-02-20 36 views
0

我有下面的XML文件:轉換XML文件,數據表C#

<?xml version="1.0" encoding="utf-8" ?> 
<font id="plejd"> 
<glyph unicode="&#x100;" glyph-name="area_add" d="string" /> 
<glyph unicode="&#x101;" glyph-name="area_bathroom" d="string2" /> 
<glyph unicode="&#x102;" glyph-name="area_cabin" d="string3" /> 
<glyph unicode="&#x103;" glyph-name="area_cinema" d="string4" /> 
</font> 

我想通過每一個項目迭代和Unicode,字形名& d添加到數據表。

我有下面的代碼,但我不知道如何獲取信息。

XDocument xdoc = XDocument.Load("PivotIcons.xml"); 
     foreach (XElement element in xdoc.Descendants()) 
     { 

     } 

我該如何做到這一點?

+0

您可以直接使用LINQ – A3006

+0

的LINQ to XML將做的工作要做。 –

回答

0

試試這個..

public static void XMLToDataTable() 
    { 
     XDocument doc = XDocument.Load(@"D:\\Sample.xml"); 

     System.Data.DataTable dt = new System.Data.DataTable(); 

     dt.Columns.Add("unicode"); 
     dt.Columns.Add("glyph_name"); 
     dt.Columns.Add("d"); 
     string[] arr = new string[3]; 

     var dr = from n in doc.Descendants("glyph") 
       select new string[]{ 
        arr[0] = n.Attribute("unicode").Value, 
        arr[1] = n.Attribute("glyph-name").Value, 
        arr[2] = n.Attribute("d").Value 
       }; 

     foreach (var item in dr) 
     { 
      dt.Rows.Add(item[0],item[1],item[2]); 
     } 
    } 
+0

謝謝!作品完美 –

0

類似:

 XElement root = XElement.Load("PivotIcons.xml"); 
     foreach (XElement element in root.Descendants("glyph")) 
     { 
      string unicode = element.Attribute("unicode").Value; 
      string glyphname = element.Attribute("glyph-name").Value; 
      string d = element.Attribute("d").Value; 

      // save to database...? 
     } 

會做這項工作。您需要將unicode格式化爲您計劃將其存儲在數據庫中的方式!