从c#/xpath获取属性值 [英] Get attribute value from c#/xpath
问题描述
我有一个app.config文件,需要获取属性值:
I have an app.config file, and need to get value of an attribute:
<param name="File" value="C:\"/>
液体XML Studio提供以下xml:
Liquid XML Studio gives the following xml:
/configuration/log4net/appender/param[1]
但是,什么C#代码可以使用xpath获取值?
However, what C# code can use xpath to get a value?
推荐答案
使用此XPath:
/configuration/log4net/appender/param[@name='File']/@value
根据您读取XML的方式,使用XPath的代码可能会有所不同.如果您使用的是 XDocument
,则可以使用 XPathEvaluate
扩展方法,如下所示:
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;
如果您使用的是 XmlDocument
,则有一个 SelectSingleNode()
方法.如果使用 XPathDocument
,则需要编译 XPathExpression
,然后将此XPath用于导航器.
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.
这篇关于从c#/xpath获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!