简体   繁体   English

从 c#/xpath 获取属性值

[英]Get attribute value from c#/xpath

I have an app.config file, and need to get value of an attribute:我有一个 app.config 文件,需要获取属性的值:

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

Liquid XML Studio gives the following xml:液体 XML Studio 给出以下 xml:

/configuration/log4net/appender/param[1]

However, what C# code can use xpath to get a value?但是,什么 C# 代码可以使用 xpath 来获取值?

Use this XPath:使用这个 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.根据您阅读 XML 的方式,使用 XPath 的代码可能会有所不同。 If you're using XDocument , you can use the XPathEvaluate extension method like so:如果您使用的是XDocument ,则可以使用XPathEvaluate扩展方法,如下所示:

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.如果您使用的是XmlDocument ,则有一个SelectSingleNode()方法。 And if you use an XPathDocument , you need to compile a XPathExpression and then use this XPath against a navigator.如果您使用XPathDocument ,则需要编译XPathExpression ,然后将这个 XPath 用于导航器。

You can use XmlDocument .您可以使用XmlDocument See XmlNode.SelectSingleNode and others.请参阅XmlNode.SelectSingleNode等。

Example:例子:

XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<configuration>
<log4net>
<appender>
<param name=""File"" value=""C:\""/>
</appender>
</log4net>
</configuration>");

var node = doc.DocumentElement.SelectSingleNode("//param[@name = 'File']/@value");

Console.WriteLine(node.Value);

It like....就如....

        var result = XDocument.Load("test.xml").Descendants("param");

        foreach (var p in result)
        {
            Console.WriteLine(p.Attribute("name"));
        }

        Console.Read();

You can use XmlDocument and a method SelectSingleNode - http://msdn.microsoft.com/en-us/library/fb63z0tw.aspx您可以使用 XmlDocument 和方法 SelectSingleNode - http://msdn.microsoft.com/en-us/library/fb63z0tw.aspx
It will find a node matching your XPath.它将找到与您的 XPath 匹配的节点。

I would do this with LINQ to XML (not with XPath)我会用 LINQ 到 XML 来做这个(不是用 XPath)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM