如何使用复杂条件在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>
目标:获取标签WHERE xml:format =“long”的文本。
提前感谢您的帮助!
答案 0 :(得分: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']
答案 1 :(得分:1)
在您的特定情况下,XML文档不在默认命名空间中,因此XPath表达式如下:
/stock/item/name
未选择任何节点。
使用强>:
/*/*/*[name()='name' and @xml:format = 'long']/text()
或使用:
string(/*/*/*[name()='name' and @xml:format = 'long'])
第一个表达式选择名称为name
的所有元素的所有文本子节点(无论名称空间如何),并且是XML文档中top元素的子元素。
第二个表达式生成XML文档中第一个元素的字符串值,使其名称为name
(无论命名空间如何),并且它是XML文档中顶部元素的子元素
基于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
答案 2 :(得分: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;