17

I'm wondering what the most elegant way is in C# to query a STRING that is valid xml using XPath?

Currently, I am doing this (using LINQ):

var el = XElement.Parse(xmlString);
var h2 = el.XPathSelectElement("//h2");
2
  • 2
    or i suppose using LinqToXML is good too... Commented Aug 17, 2009 at 18:56
  • 1
    currently, I'm doing this (using linq): var el = XElement.Parse(xmlString); var h2= el.XPathSelectElement("//h2"); Commented Aug 17, 2009 at 19:00

2 Answers 2

21

Simple example using Linq to XML :

XDocument doc = XDocument.Parse(someStringContainingXml);
var cats = from node in doc.Descendants("Animal")
           where node.Attribute("Species").Value == "Cat"
           select node.Attribute("Name").Value;

Much clearer than XPath IMHO...

Sign up to request clarification or add additional context in comments.

5 Comments

may be cleaner than XPath but does not answer the question.
@DavidAlpert, perhaps, but it was accepted nevertheless... Anyway, the question is completely subjective: how do you define "elegant"?
The original question hinges on how you define "elegant... using XPath"
Elegance inevitably involves brevity and inevitably avoids complexity.
Your way also uses more processing power, involves more reading. Other way is cleaner and less CPU.
5

Just for the record, I did not want to go with Linq2XML but XPath and found this way:

var xPathDoc = new XPathDocument(new StringReader("your XML string goes here"));

Comments

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.