[英]Using LINQ, how do I load a hierarchical XML into a POCO?
我想從分層XML數據usinq LINQ構建C#對象。 我已經將XML加載為XDocument
(首先將XML從文件中讀取到字符串中)。 我需要一些有關如何解析此內容的指導。
從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 & baby" description="test" />
<category id="3" name="home & 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; }
}
您有兩個選擇。
使用.NET序列化,在這種情況下,您需要通過使用適當的屬性(屬性名稱⇄XML元素名稱)修飾POCO類來指定XML映射。
使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.