2012-02-08 28 views
2

我想從分層XML數據usinq LINQ構建一個C#對象。 我已經將XML加載爲XDocument(通過首先將XML從文件讀取到字符串中)。 我需要一些關於如何解析這個問題的指導。使用LINQ,我如何將分層XML加載到POCO中?

例字符串從XML文件中讀取作爲

<?xml version="1.0" encoding="utf-8" ?> 
<categories version="1.0"> 
    <category id="0" name="women" description="test"> 
    <category id="01" name="tops" description="test"></category> 
    <category id="02" name="bottoms" description="test"></category> 
    <category id="03" name="accessories" description="test"></category> 
    </category> 
    <category id="1" name="men" description="test"> 
    <category id="11" name="shirts" description="test"></category> 
    <category id="12" name="trousers" description="test"></category> 
    <category id="13" name="accessories" description="test"></category> 
    </category> 
    <category id="2" name="kids &amp; baby" description="test" /> 
    <category id="3" name="home &amp; living" description="test" /> 
</categories> 

而且我有這樣的POCO類:

[DataContract] 
public class Category 
{ 
    [DataMember] 
    public int Id { get; set; } 

    [DataMember] 
    public string Name { get; set; } 

    [DataMember] 
    public string Description { get; set; } 

    [DataMember] 
    public List<Category> SubCategories { get; set; } 
} 

回答

5

你有兩個選擇。

  1. 使用.net序列,在這種情況下,你需要通過適當的屬性(屬性名⇄ XML元素名稱)裝飾你的POCO類來指定XML映射。

  2. 使用LINQ to XML(就像你想要的那樣)。在這種情況下,代碼可能是這個樣子:

    var categories = x.Root.Elements().Select(e => 
        new Category 
        { 
         Id = int.Parse(e.Attribute("id").Value), 
         Name = e.Attribute("name").Value, 
         Description = e.Attribute("description").Value, 
         SubCategories = e.Elements().Select(e1 => 
          new Category 
          { 
           Id = int.Parse(e1.Attribute("id").Value), 
           Name = e1.Attribute("name").Value, 
           Description = e1.Attribute("description").Value 
          }).ToList() 
        }).ToList(); 
    

    或者遞歸,加入了遞歸方法Parse到類:

    public static Category Parse(XElement value) 
    { 
        return new Category 
        { 
         Id = int.Parse(value.Attribute("id").Value), 
         Name = value.Attribute("name").Value, 
         Description = value.Attribute("description").Value, 
         SubCategories = value.Elements().Select(newvalue => Parse(newvalue)).ToList() 
        }; 
    } 
    

    ,並調用它像這樣:

    var categories = x.Root.Elements().Select(e => Category.Parse(e)).ToList(); 
    
+0

如果有超過兩個級別的類別,您的代碼將無法使用。 – svick 2012-02-08 14:33:44

+0

謝謝Orlin。 – 2012-02-11 05:55:15

+1

編輯我的答案包括一個遞歸選項以響應svick – Orlin 2012-02-11 10:18:18