从 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:"/>
Liquid 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:
Use this 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屋!