【问题标题】:How to write a xpath to match all elements except a particular element如何编写 xpath 以匹配除特定元素之外的所有元素
【发布时间】:2011-02-01 07:02:41
【问题描述】:

我正在编写 XSL 转换。我想编写一个模板,它匹配文档中除一个特定节点之外的所有子元素。我的 xml 看起来像这样 -

<Document>
    <NodeA></NodeA>

    <NodeB></NodeB>

    <ServiceNode></ServiceNode>

    <NodeX></NodeX>
</Document>

我想编写一个匹配除ServiceNode 之外的所有节点的模板,即NodeA 到NodeX。这个Xpath怎么写得到-

<xsl:template match="ALL Nodex Except ServiceNode">

【问题讨论】:

  • 好问题,+1。对于这个问题的四种不同可能含义,请参阅我的四种替代解决方案的答案。

标签: xml xslt xpath


【解决方案1】:

我想写一个模板 匹配除 ServiceNode 之外的所有节点 即 NodeA 到 NodeX。

如果“节点”是指元素,则使用:

<xsl:template match="*[not(self::ServiceNode)]">

如果“节点”是指任何节点(元素、文本、注释、处理指令类型):使用

<xsl:template match="node()[not(self::ServiceNode)]">

如果您只想匹配 Document 的子级,请使用:

<xsl:template match="Document/node()[not(self::ServiceNode)]">

如果您只想匹配顶部元素的子元素,请使用:

<xsl:template match="/*/node()[not(self::ServiceNode)]">

【讨论】:

    【解决方案2】:

    你最好使用这个表达式:

    *[not(self::ServiceNode)]
    

    在 XSLT 中合并:

    <xsl:stylesheet
        version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="text"/>
    
        <xsl:template match="/*">
            <xsl:apply-templates select="*[not(self::ServiceNode)]"/>
        </xsl:template>
    
        <xsl:template match="*">
            <xsl:value-of select="."/>
            <xsl:text>&#xA;</xsl:text>
        </xsl:template>
    
    </xsl:stylesheet>
    

    使用此 XML 示例:

    <Document>
        <NodeA>1</NodeA>
        <NodeB>2</NodeB>
        <ServiceNode>3</ServiceNode>
        <NodeX>4</NodeX>
    </Document>
    

    它会给出正确的结果:

    1
    2
    4
    

    【讨论】:

    • 正确。这比在 name() 或 local-name() 上进行测试要好。在 XPath 2.0 中,另一种选择是(* ServiceNode 除外)
    • 我同意。比name()好。
    【解决方案3】:

    您可以使用两个模板:

    <xsl:template match="Document/*">
       ...do something...
    </xsl:template>
    
    
    <xsl:template match="Document/ServiceNode" />
    

    后面的模板将优先,因此第一个模板将匹配除 ServiceNode 之外的所有内容。

    【讨论】:

    • 这在某些情况下可能很有用,但它不能正确回答这个问题。
    【解决方案4】:
    <xsl:template match="Document/*[name() != 'ServiceNode']">
    

    (或local-name(),如果您必须处理命名空间)

    【讨论】:

    【解决方案5】:
    /Document/*[not(name()='ServiceNode')]
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2011-05-06
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 2012-06-07
      • 2020-05-24
      相关资源
      最近更新 更多