使用 LINQ 查询 XDocument 的最佳方式?
我有一个 XML 文档,其中包含一系列如下所示的项目节点:
<data>
<item>
<label>XYZ</label>
<description>lorem ipsum</description>
<parameter type="id">123</parameter>
<parameter type="name">Adam Savage</parameter>
<parameter type="zip">90210</parameter>
</item>
</data>
我想将其 LINQ 为如下所示的匿名类型:
var mydata =
(from root in document.Root.Elements("item")
select new {
label = (string)root.Element("label"),
description = (string)root.Element("description"),
id = ...,
name = ...,
zip = ...
});
根据其 'type' 属性的值提取每个参数类型的最佳方法是什么?由于有很多参数元素,您最终会得到 root.Elements("parameter")
这是一个集合。我能想到的最好的方法就是通过下面的方法,但我觉得一定有更好的方法吗?
(from c in root.Descendants("parameter") where (string)c.Attribute("type") == "id"
select c.Value).SingleOrDefault()
I have an XML document that contains a series of item nodes that look like this:
<data>
<item>
<label>XYZ</label>
<description>lorem ipsum</description>
<parameter type="id">123</parameter>
<parameter type="name">Adam Savage</parameter>
<parameter type="zip">90210</parameter>
</item>
</data>
and I want to LINQ it into an anonymous type like this:
var mydata =
(from root in document.Root.Elements("item")
select new {
label = (string)root.Element("label"),
description = (string)root.Element("description"),
id = ...,
name = ...,
zip = ...
});
What's the best way to pull each parameter type according to the value of its 'type' attribute? Since there are many parameter elements you wind up with root.Elements("parameter")
which is a collection. The best way I can think to do it is like this by method below but I feel like there must be a better way?
(from c in root.Descendants("parameter") where (string)c.Attribute("type") == "id"
select c.Value).SingleOrDefault()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将使用 LINQ to XML 中的内置查询方法而不是 XPath。您的查询对我来说看起来很好,除了:
Element
.Value
XElement
,而不是进行多次查询。就我个人而言,我认为我什至不会为此使用查询表达式。例如:
那么:
我怀疑您会发现这比任何使用 XPath 的替代方案都更简洁,假设我已经理解您想要做什么。
I would use the built-in query methods in LINQ to XML instead of XPath. Your query looks fine to me, except that:
Element
if you're looking for direct descendants of the item.Value
XElement
for a given type, instead of having several queries.Personally I don't think I'd even use a query expression for this. For example:
Then:
I suspect you'll find that's neater than any alternative using XPath, assuming I've understood what you're trying to do.
使用XPATH - 它非常快(除了
xmlreader
- 但有很多 if's)use XPATH - it is very fast ( except
xmlreader
- but a lot of if's)