如何使用 LINQ 选择内部 XML 节点的集合?
我有以下 xml。给定 UID、制造商名称和图像布局,我想提取 xml 中存在的所有可能尺寸。
<Rules>
<UniqueID UID="123413">
<Manufacturer Name="XYZ Company">
<Image Layout="Portrait">
<Size rows="512" cols="512" price="x" />
<Size rows="1024" cols="1024" price="y" />
</Image>
</Manufacturer>
</UniqueID>
</Rules>
我现在的做法是:
XElement rules = XElement.Parse(xmlDoc.OuterXml);
var uids = rules.Elements("UniqueID")
.Where(x=> (string)x.Attribute("UID")=="123413")
.ToList();
foreach(var uid in uids)
{
var manufacturers = uid.Elements(("UniqueID")
.Where(x=> (string)x.Attribute("Name")=="XYZ Company")
.ToList();
}
依此类推,直到我收集了可能的尺寸。
所以我使用了 3 个 foreach 循环。有没有更好的方法使用 LINQ 通过一行代码来实现此目的?
I have the following xml. Given, a UID
, Manufacturer Name
and Image Layout
, I want to pull out all possible sizes that exist in the xml.
<Rules>
<UniqueID UID="123413">
<Manufacturer Name="XYZ Company">
<Image Layout="Portrait">
<Size rows="512" cols="512" price="x" />
<Size rows="1024" cols="1024" price="y" />
</Image>
</Manufacturer>
</UniqueID>
</Rules>
The way i do it right now is:
XElement rules = XElement.Parse(xmlDoc.OuterXml);
var uids = rules.Elements("UniqueID")
.Where(x=> (string)x.Attribute("UID")=="123413")
.ToList();
foreach(var uid in uids)
{
var manufacturers = uid.Elements(("UniqueID")
.Where(x=> (string)x.Attribute("Name")=="XYZ Company")
.ToList();
}
and so on until I have a collection of the possible sizes.
So I am using 3 foreach loops. Is there a better way acheive this with probably one line of code, using LINQ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然有点拗口,但您可以使用 XPathSelectElements:
显然,您可以使用字符串格式来动态插入 @UID 和 @Name 的值。
确保包含
System.Xml.XPath
。It's a little bit of a mouthful, but you can use XPathSelectElements:
Obviously, you could use string formatting to dynamically insert values for @UID and @Name.
Make sure to include
System.Xml.XPath
.我喜欢 James 的 XPath 方法。如果您继续堆叠 LINQ,它可能会是什么样子。
sizes
最终成为 IEnumerable(2 项)I like James's XPath approach. Here is what it might look like if you just keep stacking LINQ.
sizes
ends up being IEnumerable (2 items)试试这个(使用 XPath):
Try this(used XPath):