简体   繁体   English

xpath从xml文档返回值

[英]xpath to return value from xml doc

I'm wondering if there is a way to do the following with one xpath expression: I have an XML doc similar to this but with many 'results', 我想知道是否有一种方法可以对一个xpath表达式进行以下操作:我有一个与此类似的XML文档,但是有很多“结果”,

<result>
    <id>1</id>
    <name>joe</name>
</result>
<result>
    <id>2</id>
    <name>jim</name>
</result>

I'm passing a variable into a C# utility along with the xml, and want to return the name where the id = the variable. 我要将变量与xml一起传递到C#实用程序中,并想返回id =变量的名称。 I could loop through the xml until reach what I'm after but if there's a handy xpath way to do it I'm listening... thanks 我可以遍历xml直到达到所需的状态,但是如果有方便的xpath方式可以实现,那么我在听...谢谢

Assuming you have a root element in there like "results" that XPath can validate, and that you don't have any other nodes named "result"... 假设您在其中有一个根元素,例如XPath可以验证的“结果”,并且您没有其他名为“结果”的节点...

//result[id=1]/name

Or you could get the text outright, instead of it being returned in a node 或者您可以直接获取文本,而不是在节点中将其返回

//result[id=1]/name/text()

And if you want to make sure that there's only one result, you could surround it with parens and put a [1] after 如果要确保只有一个结果,可以用括号包围它,并在其后放置[1]

(//result[id=1]/name/text())[1]

I would also recommend testing with one of the xpath test sites out there like this one , but beware that different xpath/xml parsers sometimes behave differently. 我还建议测试与XPath的考点有像一个这一个 ,但要注意的是不同的XPath / XML解析器有时表现不同。

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

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