xml 根据内容选择子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/718531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:26:05  来源:igfitidea点击:

Select child nodes based on their contents

xmlxsltxpathnodes

提问by krasnaya

XML snippet:

XML 片段:

<AA>
  <BB>foo</BB>
  <CC>bar</CC>
  <DD>baz</DD>
  <EE>bar</EE>
</AA>

How do I select all the child nodes of <AA>that have baras its contents? In the example above, I'd want to select <CC>and <EE>. I'm thinking the solution is something like:

如何选择的所有子节点<AA>已经bar为它的内容?在上面的示例中,我想选择<CC><EE>。我认为解决方案是这样的:

<xsl:template match="AA">
  <xsl:for-each select="???" />
</xsl:template>

回答by Dimitre Novatchev

One of the simplest solutions to the OP's question is the following XPath expression:

OP 问题的最简单解决方案之一是以下 XPath 表达式

*/*[.='bar']

Do note, that no XSLT instruction is involved -- this is just an XPath expression, so the question could only be tagged XPath.

请注意,不涉及 XSLT 指令——这只是一个 XPath 表达式,因此问题只能标记为 XPath。

From here on, one could use this XPath expression in XSLT in various ways, such as to apply templates upon all selected nodes.

从这里开始,可以以各种方式在 XSLT 中使用此 XPath 表达式,例如在所有选定节点上应用模板

For example, below is an XSLT transformation that takes the XML document and produces another one, in which all elements - children of <AA>whose contents is not equal to "bar"are deleted:

例如,下面是一个 XSLT 转换,它采用 XML 文档并生成另一个文档,其中删除所有元素 -<AA>其内容不等于的子元素"bar"

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

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

    <xsl:template match="AA">
      <xsl:copy>
         <xsl:apply-templates select="*[. = 'bar']"/>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the original XML document:

当此转换应用于原始 XML 文档时

<AA>
    <BB>foo</BB>
    <CC>bar</CC>
    <DD>baz</DD>
    <EE>bar</EE>
</AA>

the wanted result is produced:

产生了想要的结果

<AA>
   <CC>bar</CC>
   <EE>bar</EE>
</AA>

Do note:

请注意

In a match pattern we typically do not need to specify an absolute XPath expression, but just a relative one, so the full XPath expression is naturally simplified to this match pattern:

在匹配模式中,我们通常不需要指定绝对 XPath 表达式,而只需要指定一个相对表达式,因此完整的 XPath 表达式自然会简化为这种匹配模式:

*[. = 'bar']