用于检查多个节点的XPath查询都具有所需的值

时间:2012-11-07 10:20:09

标签: xml xpath

我的示例XML如下:

<FileList>
  <File>
    <Name>20120427_1.pdf</Name>
    <Size>654441</Size>
    <Property>
      <Name>Country</Name>
      <Value>United States</Value>
    </Property>
   </File>
   <File>
    <Name>Name2</Name>
    <Size>2147483647</Size>
    <Property>
      <Name>Name4</Name>
      <Value>Value4</Value>
    </Property>
    <Property>
      <Name>Name5</Name>
      <Value>Value5</Value>
    </Property>
    <Property>
      <Name>Name6</Name>
      <Value>Value6</Value>
    </Property>
  </File>
  <File>
    <Name>Name3</Name>
    <Size>2147483647</Size>
    <Property>
      <Name>Name7</Name>
      <Value>Value7</Value>
    </Property>
    <Property>
      <Name>Name8</Name>
      <Value>Value8</Value>
    </Property>
    <Property>
      <Name>Country</Name>
      <Value>UK</Value>
    </Property>
  </File>
</FileList>

要求是每个文件节点在Propery / Name元素中都有一个Country值。到目前为止,我已经创建了一个XPath查询:

/FileList/File/Property/Name/text()='Country'

当answer应该为false时,查询正在查看所有节点。如何更改它以便检查每个“文件”节点?

2 个答案:

答案 0 :(得分:1)

使用

not(/*/File[not(Property/Name = 'Country')])

基于XSLT的验证:

此转化

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy-of select=
     "not(/*/File[not(Property/Name = 'Country')])"/>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<FileList>
  <File>
    <Name>20120427_1.pdf</Name>
    <Size>654441</Size>
    <Property>
      <Name>Country</Name>
      <Value>United States</Value>
    </Property>
   </File>
   <File>
    <Name>Name2</Name>
    <Size>2147483647</Size>
    <Property>
      <Name>Name4</Name>
      <Value>Value4</Value>
    </Property>
    <Property>
      <Name>Name5</Name>
      <Value>Value5</Value>
    </Property>
    <Property>
      <Name>Name6</Name>
      <Value>Value6</Value>
    </Property>
  </File>
  <File>
    <Name>Name3</Name>
    <Size>2147483647</Size>
    <Property>
      <Name>Name7</Name>
      <Value>Value7</Value>
    </Property>
    <Property>
      <Name>Name8</Name>
      <Value>Value8</Value>
    </Property>
    <Property>
      <Name>Country</Name>
      <Value>UK</Value>
    </Property>
  </File>
</FileList>

评估XPath表达式并生成所需的正确结果:

false

<强>解释

使用 double negation law

答案 1 :(得分:0)

要获取没有国家/地区的文件,请使用

/FileList/File[not(Property[Name='Country'])]

要获取其名称,您可以使用

/FileList/File[not(Property[Name='Country'])]/Name/text()