【问题标题】:How to do I retrieve a particular XML element based on its child elements in XSLT 2.0?如何根据 XSLT 2.0 中的子元素检索特定的 XML 元素?
【发布时间】:2011-12-21 07:04:23
【问题描述】:

这是我的 XML 文档(小 sn-p)。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">

<w:body>
    <w:p> <!-- Current Node -->
        <w:r>
            <w:t>
                 This is the
            </w:t>
        </w:r>
        <w:r>
            <w:pict>
                <w:p>
                    <w:r>
                        <w:t>
                            I dont need this
                        </w:t>
                    </w:r>
                </w:p>
            </w:pict>
        </w:r>

        <w:r>
            <w:pict>
                <w:p>
                    <w:r>
                        <w:t>
                            I dont need this too
                        </w:t>
                    </w:r>
                </w:p>
            </w:pict>
        </w:r>

        <w:r>
            <w:t>
                 text that i need to retrieve...
            </w:t>
        </w:r>
    </w:p>
</w:body>
</w:document>   

在这里,我想检索 &lt;w:r&gt;&lt;w:t&gt; 值,并且 &lt;w:r&gt; 中不应包含子 &lt;w:pict&gt;。因此,根据我上面的 XML 文档,我想生成以下输出:

<paragraph>This is the text that i need to retrieve...</paragraph>

这是我的 XSLT sn-p(请告诉我这个 XSLT 需要进行哪些更改才能获得上述格式):

<xsl:choose>
    <xsl:when test="self::w:p[//w:r/w:t[not(ancestor::w:pict)]]">

        <Paragraph>
            <xsl:apply-templates select="./w:t[not(ancestor::w:pict)]" />
        </Paragraph>
    </xsl:when>
</xsl:choose>

<xsl:template match="w:t">
    <xsl:value-of select="." />
</xsl:template>

但它不起作用......

请指导我摆脱这个问题。

【问题讨论】:

  • 文本“我不需要这个”包含在 &lt;w:r&gt;&lt;w:t&gt; 中,而 &lt;w:r&gt; 不包含子 &lt;w:pict&gt;。你能再澄清一下你的要求吗?听起来您需要检查祖先元素,而不是子元素。
  • @TimC : 是的 tim.I 想要获得其祖先不等于 值。

标签: xml xslt xpath xslt-2.0


【解决方案1】:

在您当前的示例中,如果您当前的节点是 /w:document/w:body/w:p,您可以使用以下命令检索所有所需的节点:

w:r/w:t

但是,如果您需要在任何级别检索 w:r/w:t,但没有 w:pict 作为祖先,您可以使用 ancestor 轴:

.//w:r/w:t[not(ancestor::w:pict)]

【讨论】:

    【解决方案2】:

    假设您正在使用带有 xsl:apply-templates 的自上而下递归下降以经典 XSLT 方式处理此问题,那么排除具有 w:pict 子级的 w:r 的方法如下:

    <xsl:template match="w:r[w:pict]"/>
    

    我似乎记得遇到过一个案例,如果 w:r 唯一的子元素是 w:pict,我想排除它。在这种情况下,解决方案是

    <xsl:template match="w:r[w:pict and count(*)=1]"/>
    

    【讨论】:

      【解决方案3】:

      您还可以使用过滤来检索所有没有w:pict 元素的w:r 节点

      <xs:for-each select="//w:r[count(w:pict) = 0]">
          <xsl:value-of select="w:paragraph" />
      </xsl:for-each>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-15
        • 2022-10-04
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        • 2019-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多