繁体   English   中英

带条件的xpath

[英]xpath with condition

如何使用复杂条件在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”的文本。

在此先感谢您的帮助!

看看这个: 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表达式如下:

/stock/item/name

不选择任何节点

用途

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

或使用

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

第一个表达式选择名称为name的所有元素的所有文本子节点(无论命名空间如何),并且是XML文档中top元素的子元素。

第二个表达式生成XML文档中第一个元素的字符串值,使其名称为name (无论命名空间如何),并且它是XML文档中top元素的子元素。

基于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

拥有以下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;

暂无
暂无

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

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