如何使用Xml属性值获取关联的元素? [英] How can I use an Xml attribute value to get an associated element?
问题描述
我有一个很大的Xml文件,其中包含我的数据.我需要以编程方式从中获取数据.这是一个小得多的文件,但结构完全相同...
I have a large Xml file containing my data. I need to programmatically get data from it. Here is a much smaller file but with the exact same structure ...
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<colours xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Red>
<Shade id="1">
<colour>crimson</colour>
</Shade>
<Shade id="2">
<colour>raspberry</colour>
</Shade>
<Shade id="3">
<colour>lava</colour>
</Shade>
<Shade id="4">
<colour>scarlet</colour>
</Shade>
</Red>
<Green>
<Shade id="1">
<colour>asparagus</colour>
</Shade>
<Shade id="2">
<colour>emerald</colour>
</Shade>
<Shade id="3">
<colour>lime</colour>
</Shade>
<Shade id="4">
<colour>avocado</colour>
</Shade>
</Green>
<Blue>
<Shade id="1">
<colour>cyan</colour>
</Shade>
<Shade id="2">
<colour>sapphire</colour>
</Shade>
<Shade id="3">
<colour>powder</colour>
</Shade>
<Shade id="4">
<colour>iris</colour>
</Shade>
</Blue>
</colours>
我需要解决一个单独的阴影,例如知道颜色红色"和阴影ID(例如"3").
I need to resolve an individual shade, knowing the colour e.g. "Red" and the Shade id e.g."3".
以下代码计算了阴影元素的数量,这是我需要的,但是超出此范围的任何内容对我来说仍然是个谜.
The following code counts the number of shade elements, which is something I need but anything beyond this is still a mystery to me.
string filepath = "C:/Documents/Data.xml";
XElement MyData = XElement.Load(filepath);
int count = MyData.Elements("Red")
.Elements("shade")
.Count();
Console.Write(count);
Console.ReadKey();
推荐答案
除了使用XPath谓词外,如其他答案所示,您可以使用LINQ Where()
方法为某些条件过滤元素:
Besides using XPath predicate, as demonstrated in the other answer, you can use LINQ Where()
method to filter element for certain criteria :
int count = MyData.Elements("Red")
.Elements("Shade")
.Where(o => (int?)o.Attribute("id") == 3)
.Count();
Dotnetfiddle Demo
请注意,XML区分大小写,因此"Shade"不等于"shade"
这篇关于如何使用Xml属性值获取关联的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!