XPath 排除某些 XML 元素? [英] XPath to exclude certain XML elements?

查看:28
本文介绍了XPath 排除某些 XML 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经阅读了很多(可能是全部)关于 XPath 中排除元素的帖子,但我只是不明白这一点.我不知道为什么.

I have now read many (maybe all) posts on excluding elements in XPath and I just do not get this working. I have no clue why.

假设我有以下结构:

<root>
  <elemA>
      Hello World!
  </elemA>
  <elemB>
      This is awesome!
      <elemC>Really!</elemC>
  </elemB>
</root>

不,我想要除 elemC 之外的所有元素.

No I want all elements except elemC.

根据我所阅读的内容,我尝试了以下 XPath:

Based on what I have read, I tried the following XPath:

选项 1:

//*[not(self::elemC)]

选项 2:

//*[not(name()='elemC')]

选项 3:

//*[name()!='elemC']

我不知道为什么这不起作用,但怀疑一些愚蠢的错误.如果我做完全相反的事情(即省略 not!),XPath 会正确选择 elemC 元素.

I have no clue why this is not working, but suspect some stupid mistake. If I do the exact opposite (i.e. leaving out the not or !) the XPath correctly selects the elemC element.

结果应该是这样的:

<root>
  <elemA>
      Hello World!
  </elemA>
  <elemB>
      This is awesome!
  </elemB>
</root>

推荐答案

XPath 供选择.您要选择的内容在您的 XML 文档中不存在.

您需要另一个工具(例如 XSLT)来根据输入的 XML 文档生成 XML 输出文档.XSLT 可以通过身份转换轻松生成您想要的输出,并辅以一个简单的模板,该模板禁止复制您不想要的元素 (elemC):

You need another tool such as XSLT to generate an XML output document based on an input XML document. XSLT can generate your desired output trivially via the identity transformation supplemented with a simple template that suppresses the copying of the element that you do not want (elemC):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="elemC"/>
</xsl:stylesheet>

仅靠 XPath 无法帮助您.

这篇关于XPath 排除某些 XML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆