[英]Linq2XML Create Object Model
如果我有以下xml;
<productList>
<product>
<id>1</id>
<name>prod 1</name>
</product>
<product>
<id>2</id>
<name>prod 2</name>
</product>
<product>
<id>3</id>
<name>prod 3</name>
</product>
</productList>
我將如何使用Linq2XML創建對象層次結構?
我已經嘗試過了
var products = from xProducts in xDocument.Descendants("root").Elements("productList")
select new
{
product = from xProduct in xProducts.Elements("product")
select new
{
id = xProduct.Element("id").Value,
name = xProduct.Element("name").Value
}
}
但是,這會產生錯誤,因為我認為該product
被聲明了多次。
我想結束一個這樣的對象;
ProductList
List<product>
id
name
我沒有模型可以進入這些模型,因此我需要使用var。
編輯
如果僅說出名稱或ID,則代碼有效。 僅當我嘗試同時獲取兩個字段時,它才會失敗。
關於您的錯誤,您正在使用Silverlight嗎? 這不支持匿名類型。 無論如何,Linq-to-XML使用流利的語法而不是查詢語法會更好地工作。 定義合適的ProductList和Product類,以下方法應該起作用:
class ProductList : List<Product>
{
public ProductList(items IEnumerable<Product>)
: base (items)
{
}
}
class Product
{
public string ID { get; set;}
public string Name{ get; set;}
}
var products = xDocument.Desendants("product");
var productList = new ProductList(products.Select(s => new Product()
{
ID = s.Element("id").Value,
Name= s.Element("name").Value
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.