简体   繁体   English

使用c#获取XPAth的xml属性

[英]Getting an xml attribute with XPAth using c#

I'm trying to get an attribute from the XML but I'm getting an error: 我正在尝试从XML获取属性,但我收到一个错误:

Expression must evaluate to a node-test 表达式必须评估为节点测试

I'm new to XPath. 我是XPath的新手。

XML file example: XML文件示例:

<Message>
   <Head>
      <Sender Identifier="id" ref=""/>
   </Head>
</Message>

Code: 码:

XPathDocument xDoc = new XPathDocument("documentName.xml");
XPathNavigator nav = xDoc.CreateNavigator();
XPathNodeIterator xpathNode = nav.Select("/Message/Head/Sender/[@Identifier]");
//This is where I get the error.

And I'm also not sure how to display the attribute value. 而且我也不确定如何显示属性值。

It should be 它应该是

/Message/Head/Sender[@Identifier]
                    ^
                    |->no need of / here since Identifier is an attribute of sender

So, 所以,

/Message/Head/Sender[@Identifier] would only select Sender if it has an Identifier attribute /Message/Head/Sender[@Identifier]只有在具有Identifier属性的情况下才会选择Sender

/Message/Head/Sender[@Identifier='id'] would only select Sender if it has an Identifier attribute with value id /Message/Head/Sender[@Identifier='id']只有在具有值idIdentifier属性时才会选择Sender

Here is the wonderful tool to evaluate Xpath of the given XML 这是评估给定XML的Xpath的绝佳工具

go to this link http://www.xmltoolbox.com/ and try to paste your xml in the textarea and move your cursor to the node you want Xpath.Xpath will be generated below 转到此链接http://www.xmltoolbox.com/并尝试将您的xml粘贴到textarea中并将光标移动到您希望在下面生成Xpath.Xpath的节点

 XmlIO xml = new XmlIO(xmlPath);
                ProductName = xml.SelectNodeValue(@"//PRODUCTINFO/Application/@ProductName");
                IDictionary<string, string> keyValList = xml.SelectNodesList(@"//PRODUCTINFO/Application/Parameters");

Take a look 看一看

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

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