var subset = from item in document.Descendants("Id")
where item.Value == itemId.ToString()
select new PurchaseItem() {
Id = int.Parse(item.Parent.Element("Id").Value),
Name = item.Parent.Element("Name").Value,
Description = item.Parent.Element("Description").Value,
Price = int.Parse(item.Parent.Element("Price").Value)
};
XML的结构如下:
<Items>
<Item>
<Id></Id>
<Name></Name>
<Description></Description>
<Price></Price>
</Item>
</Items>
Id,价格都是整数值。名称和描述是字符串。
我发现Linq to XML
非常适合我用过的内容,这只是一个片段。但是,另一方面,我感觉它应该或可能更清洁。这个片段似乎是这个片段中最明显的问题。
有什么建议吗?
答案 0 :(得分:13)
实际上,施法比调用int.Parse
更好的IMO。这是我写你的查询的方式:
string id = itemId.ToString(); // We don't need to convert it each time!
var subset = from item in document.Descendants("Id")
where item.Value == id
let parent = item.Parent
select new PurchaseItem
{
Id = (int) parent.Element("Id"),
Name = (string) parent.Element("Name"),
Description = (string) parent.Element("Description"),
Price = (int) parent.Element("Price")
};
答案 1 :(得分:1)
我假设您还有一个“Items”节点?
你可以这样做,假设你使用XElement.Load()加载文档
var subset = from item in document.Elements("Item")
where item.Element("Id").Value == itemId.ToString()
select new PurchaseItem() {
Id = int.Parse(item.Element("Id").Value),
Name = item.Element("Name").Value,
Description = item.Element("Description").Value,
Price = int.Parse(item.Element("Price").Value)
};
不是更好,但更容易阅读!
答案 2 :(得分:1)
在您的示例中,您可以通过找到<Item/>
元素而不是<Id/>
来整理一下,以避免每次都获得Parent
:
var subset = from item in document.Descendants("Item")
where item.Element("Id").Value == itemId.ToString()
select new PurchaseItem()
{
Id = int.Parse(item.Element("Id").Value),
Name = item.Element("Name").Value,
Description = item.Element("Description").Value,
Price = int.Parse(item.Element("Price").Value)
};
答案 3 :(得分:1)
考虑为PurchaseItem
编写一个带有XML元素的新构造函数,所以你可以写:
select new PurchaseItem(item.Parent);