Linq-XML 总是那么混乱吗?
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和price都是整数值。名称和描述是字符串。
我发现 Linq to XML
非常适合我的用途,这只是一个片段。但是,另一方面,我觉得它应该或可以更干净。选角似乎是此片段中最明显的问题。
有什么建议吗?
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)
};
The structure of the XML is as follows:
<Items>
<Item>
<Id></Id>
<Name></Name>
<Description></Description>
<Price></Price>
</Item>
</Items>
Id, and price are both integer values. Name and description are strings.
I've found Linq to XML
great for what I've used it for, this is just a snippet. But, on the other hand I get the feeling it should or could be cleaner. The casting seems the most obvious issue in this snippet.
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际上,在我看来,强制转换比调用 int.Parse 更好。以下是我如何编写您的查询:
Actually it would be better IMO to cast than to call
int.Parse
. Here's how I would write your query:我假设您也有一个“Items”节点?
您可以执行类似的操作,假设您使用 XElement.Load() 加载文档,
虽然不是更好,但更容易阅读!
I assume that you have an "Items" node as well?
You could do something like this, assuming that you are loading the document using XElement.Load()
Not a lot better, but much easier to read!
在您的示例中,您可以通过查找
元素而不是
来进行一些整理,以避免获取每次父级
:In your example you can tidy up a little bit by finding the
<Item/>
element rather than the<Id/>
to avoid getting theParent
each time:考虑为采用 XML 元素的
PurchaseItem
编写一个新的构造函数,这样您就可以编写:Consider writing a new constructor for
PurchaseItem
that takes the XML element, so you can write: