C# 获取XML节点属性并设置为列表的属性<;myType>;?
XML示例:C# 获取XML节点属性并设置为列表的属性<;myType>;?,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,XML示例: <Root> <Product value="Candy"> <Item value="Gum" price="1.00"/> <Item value="Mints" price="0.50"/> </Product> </Root> 在我的主要课程中,我有一个列表: var Candies = new List<CandyItems>; 但似乎我可以用纯LINQ更简洁地做到
<Root>
<Product value="Candy">
<Item value="Gum" price="1.00"/>
<Item value="Mints" price="0.50"/>
</Product>
</Root>
在我的主要课程中,我有一个列表:
var Candies = new List<CandyItems>;
但似乎我可以用纯LINQ更简洁地做到这一点。或者有其他推荐的方法吗?这样的方法怎么样(加载文档后): 注意:忽略所有错误处理。尝试以下操作:-
XDocument xdoc = XDocument.Load(@"Path\Candies.xml");
List<CandyItems> Candies = xdoc.Descendants("Item")
.Select(x => new CandyItems
{
Value = (string)x.Attribute("value"),
Price = (string)x.Attribute("price")
}).ToList();
使用怎么样?谢谢!这正是我要找的!
//Get list of Items within <Product value="Candy">
XElement tempCandies = XDocument.Load("file.xml").Root.Elements("Product").Single(c => c.Attributes("value") == "Candy").Descendants("Item");
//Loop through the elements
foreach(var item in tempCandies){
Candies.Add(new CandyItems{Value = item.Attributes("value"), Price = item.Attributes("price")});
}
var candies =
xdoc.Root.Elements("Product")
.Where(p => p.Attribute("value").Value == "Candy")
.SelectMany(p => p.Descendants("Item").Select(i => new CandyItems {
Value = i.Attribute("value").Value,
Price = i.Attribute("price").Value }));
XDocument xdoc = XDocument.Load(@"Path\Candies.xml");
List<CandyItems> Candies = xdoc.Descendants("Item")
.Select(x => new CandyItems
{
Value = (string)x.Attribute("value"),
Price = (string)x.Attribute("price")
}).ToList();
<Root>
<Product value="Candy">
<Item value="Gum" price="1.00"/>
<Item value="Mints" price="0.50"/>
</Product>
<Product value="Chocolate">
<Item value="MilkChocolate" price="7.00"/>
<Item value="DarkChocolate" price="10.50"/>
</Product>
</Root>
List<CandyItems> Candies = xdoc.Descendants("Item")
.Where(x => (string)x.Parent.Attribute("value") == "Candy")
.Select(x => new CandyItems
{
Value = (string)x.Attribute("value"),
Price = (string)x.Attribute("price")
}).ToList();