Thorin Oakenshield
Thorin Oakenshield

Reputation: 14672

How to find attribute value

I need to find an inner text of an element inside an XmlDocument and return it's Xpath. for example, searching for "ThisText" inside :

<xml> 
<xml2 val="ThisText"></xml2> 
</xml> 

should return the Xpath of xml2

what's the most efficient way of doing this in c#?

Upvotes: 1

Views: 192

Answers (1)

Jens Granlund
Jens Granlund

Reputation: 5070

Try this:

string xml = "<xml><xml2 val=\"ThisText\"/><xml2 val=\"ThatText\"/></xml>";
var doc = XDocument.Parse(xml);
var node = doc.Descendants().First(x => x.Attribute("val") != null 
            && x.Attribute("val").Value == "ThisText");
Trace.WriteLine(node);

Upvotes: 1

Related Questions