1

I'm wondering whether there is a way using C# which enables me to return all the inner values within an XML file matching a given XPath query.

Let's suppose that we have the following Xml file named exampleWithFruits.xml:

<fruits>
   <bananas>
      <banana id="1" color="yellow" price="0.5" />
      <banana id="2" color="yellow" price="0.4" />
      <banana id="3" color="yellow" price="0.6" />
   </bananas>
   <apples>
      <apple id="1" color="red" price="0.5" />
      <apple id="2" color="red" price="0.4" />
      <apple id="3" color="green" price="0.6" />
      <apple id="4" color="yellow" price="0.4" />
   </apples>
   <oranges>
      <orange id="1" color="orange" price="0.5" />
      <orange id="2" color="orange" price="0.5" />
   </oranges>
</fruits>

Something like following below:

string xmlFilePath = "exampleWithFruits.xml";
string xPathQuery = "//fruits/apples//@color"
string[] matchingValues = interestingFunction(xmlFilePath, xPathQuery);
//for instance we would get something like : matchingValues = {red, red, green, yellow}

To sum up, I would like to know how to create a function such as interestingFunction

Thx

1 Answer 1

1

One way to do this is to use System.Xml.XPath.Extensions.XPathEvaluate.

E.g.

string xmlFilePath = "exampleWithFruits.xml";
string xPathQuery = "//fruits/apples//@color";

var doc = XDocument.Load(xmlFilePath);
IEnumerable att = (IEnumerable)doc.XPathEvaluate(xPathQuery);
string[] matchingValues = att.Cast<XAttribute>().Select(x => x.Value).ToArray();

Or if you prefer XmlDocument:

var doc = new XmlDocument();
doc.Load(xmlFilePath);
string[] matchingValues = doc.SelectNodes(xPathQuery).Cast<XmlAttribute>().Select(x => x.Value).ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

Where can I find System.Xml.XPath.Extensions.XPathEvaluate?
@Pamplemousse Add a reference to the assembly System.Xml.Linq.dll
I'm able to add System.Xml.XPath.Extensions but not System.Xml.XPath.Extensions.XPathEvaluate after adding the System.Xml.Linq.dll assembly reference.
Alright! I found it on MSDN reference. It is simply: using System.Xml.XPath;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.