xml - xpath根据 child 的属性值删除节点

标签 xml xslt xpath attributes

我有这个 xml 代码:

<osm>
  <count>
    <tag k="nodes" v="608"/>   
  </count>
  <node>
    <tag k="addr:housenumber" v="5-10"/>
    <tag k="addr:postcode" v="BA1 2BX"/>
  </node>
  <way>
    <tag k="amenity" v="nightclub"/>
    <tag k="facebook" v="https://www.facebook.com"/>
  </way>
  <node>
    <tag k="amenity" v="cafe"/>
    <tag k="addr:postcode" v="BS3 2BX"/> 
  </node>
  <node>
    <tag k="amenity" v="school"/>
    <tag k="facebook" v="https://www.facebook.com"/>
  </node>
  <way>
    <tag k="amenity" v="church"/>
    <tag k="addr:postcode" v="BAX 5RT"/>   
  </way>
</osm>

我需要删除 <osm> 下面的所有节点其中包含 <tag>具有属性 k 的节点值为 'addr:postcode' :

<osm>
  <count>
    <tag k="nodes" v="608"/>   
  </count>
  <way>
    <tag k="amenity" v="nightclub"/>
    <tag k="facebook" v="https://www.facebook.com"/>
  </way>
  <node>
    <tag k="amenity" v="school"/>
    <tag k="facebook" v="https://www.facebook.com"/>
  </node>
</osm>

我已经尝试了围绕此查询的许多排列,但它返回 <tag> 的每次出现。 :

<xsl:apply-templates select="osm/*/tag[not(@k='addr:postcode')]"> 

我想我需要找到 parent ,但这就是我的知识耗尽的地方。

最佳答案

你是对的;您需要选择标签的父级。为此,只需选择 * 并将 标签 放入谓词中。

示例...

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

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="osm">
    <xsl:copy>
      <xsl:apply-templates select="*[not(tag/@k='addr:postcode')]"/>      
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

这里的工作演示:http://xsltransform.net/pNmBy23

或者,您可以添加匹配的模板...

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

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*[tag/@k='addr:postcode']"/>

</xsl:stylesheet>

这将产生相同的输出。 (http://xsltransform.net/pNmBy23/1)

关于xml - xpath根据 child 的属性值删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799789/

相关文章:

sql - 在 SQL Server 2005 中按 XML 中的值进行查询

xml - 我们可以使用 shell 脚本(或任何脚本/编程)在 Linux 上使用 XSLT 转换 XML 吗?

xslt - 如何向 XSLT for-each 语句添加多个过滤器?

python - lxml.xpath 中的正则表达式

java - 如何返回到 XPath 中的直接父级并获取文本?

sql-server - 无法在 SQL Server 中将 TEXT 转换为 XML

xml - 如何从 Conref 表创建 "Piecemail"表

xslt - 为什么我的 XSLT 变量没有替换它们的值?

xml - 按 XSL 中的 2 个字段分组

c - lixml2 C xpath 失败并显示 "invalid expression"