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>
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();
Besides using XPath predicate, as demonstrated in the other answer, you can use LINQ
Where()
method to filter element for certain criteria :Dotnetfiddle Demo
Notice that XML is case-sensitive, so "Shade" is not equal to "shade"
Try this
If I understand correctly, you'd like to find how many elements have a given Shade id.
You can use XPath queries against Linq to XML's XElement.
Try this:
Let me know if this is what you want. If not, please comment and I'll modify my answer.
Cheers