XPath与条件

3

如何使用复杂条件在Xpath中获取元素?

例如:

<?xml version="1.0" encoding="UTF-8"?>
<stock xmlns="http://localhost/aaabbb">
<item item-id="1">
 <name xml:format="short">This is a short name</name>
 <name xml:format="long">This is a LONG name</name>
</item>
</stock>

目标:获取xml:format="long"的<p>标签内的文本。

非常感谢您的帮助!

3个回答

6
请看这个: http://www.w3schools.com/xpath/xpath_syntax.asp。您所要求的示例代码如下:
XML文档:
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore> 

XPATH:

//title[@lang='eng']    Selects all the title elements that have an attribute named lang with a value of 'eng'

所以你应该这样做:
//name[@xml:format='long']

这个答案没有展示一个真正选择所提供的XML文档中想要节点的XPath表达式。它没有提到文档的一个非常特定的属性,这使得在没有关于命名空间的额外知识的情况下指定XPath表达式变得困难。最后,推荐使用www.w3schools.com并不是好的帮助,因为它们不是权威来源(XPath的唯一权威来源是相应的W3C规范),并且经常提供错误信息。在这里了解更多:http://w3fools.com/ - Dimitre Novatchev

1

在您的特定情况下,XML文档不在默认命名空间中,因此XPath表达式如下:

/stock/item/name

未选择任何节点

用途

/*/*/*[name()='name' and @xml:format = 'long']/text()

或者使用:

string(/*/*/*[name()='name' and @xml:format = 'long'])

第一个表达式选择XML文档顶层元素的所有子元素中,名为name(不考虑命名空间)的所有文本节点的元素。

第二个表达式生成XML文档顶层元素的第一个名为name(不考虑命名空间)的子元素的字符串值。

基于XSLT的验证:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
     <xsl:copy-of select="/*/*/*[name()='name' and @xml:format = 'long']/text()"/>
===========
     <xsl:copy-of select="string(/*/*/*[name()='name' and @xml:format = 'long'])"/>
 </xsl:template>
</xsl:stylesheet>

当应用此转换到提供的 XML 文档时:

<stock xmlns="http://localhost/aaabbb">
    <item item-id="1">
        <name xml:format="short">This is a short name</name>
        <name xml:format="long">This is a LONG name</name>
    </item>
</stock>

两个XPath表达式被评估,第一个选择的元素和第二个产生的字符串结果被复制到输出中:

This is a LONG name
===========
This is a LONG name

0

拥有以下XML文件

<?xml version="1.0" encoding="UTF-8"?>
<stock xmlns="http://localhost/aaabbb">
<item item-id="1">
 <name xml:format="short">This is a short name</name>
 <name xml:format="long">This is a LONG name</name>
</item>
</stock>

首先指定节点列表的 xPath

XmlNodeList nodeList = root.SelectNodes("/stock/item");

第二步是指定您想要的名称节点:(具有“Long”属性值的节点)

XmlNode name = nodeList.Item(0).SelectSingleNode(string.Format("/stock/item/name[@xml:format="Long"]"));

第三步,获取此节点内的文本:

string result = name.InnerText;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接