Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attribute value from c#/xpath

Tags:

c#

.net

xml

xslt

xpath

I have an app.config file, and need to get value of an attribute:

<param name="File" value="C:\"/>

Liquid XML Studio gives the following xml:

/configuration/log4net/appender/param[1]

However, what C# code can use xpath to get a value?

like image 601
gss3 Avatar asked Jul 15 '11 08:07

gss3


1 Answers

Use this XPath:

/configuration/log4net/appender/param[@name='File']/@value

Depending on how you read the XML, the code for using the XPath may differ a bit. If you're using XDocument, you can use the XPathEvaluate extension method like so:

var eval = xml.XPathEvaluate("/configuration/log4net/appender/param[@name='File']/@value");
var value = ((IEnumerable)eval).OfType<XAttribute>().Single().Value;

If you're using XmlDocument, there is a SelectSingleNode() method. And if you use an XPathDocument, you need to compile a XPathExpression and then use this XPath against a navigator.

like image 52
Lucero Avatar answered Sep 21 '22 06:09

Lucero