XSL - 检查同一级别的节点

时间:2014-11-21 16:37:37

标签: xml xslt

我在XML中有这个结构:

<report>
  <text>
    <chapter>1</chapter>
    <chapter>2
        <section>2.1</section>
    </chapter>
    <chapter>3</chapter>
  </text>
</report>

在我的DTD中,我有:

 <!ELEMENT text (#PCDATA | chapter |section)*>

因此,在我的XSL中,我希望保证在进行转换之前我没有chaptersection在同一级别。所以,我不能拥有这个

<report>
  <text>
    <chapter>1</chapter>
    <chapter>2
        <section>2.1</section>
    </chapter>
    <section>3</section>
  </text>
</report>

我的XSL

<xsl:template match="chapter">

    <div class="chapter">   
        <h2> 
            <xsl:apply-templates select="chapter-title"/>
        </h2>       
        <hr/>
        <xsl:apply-templates select="text() | section "/>
    </div>
</xsl:template> 
<xsl:template match="section">
    <div class="section">
        <h3>  
            <xsl:apply-templates select="section-title"/>
        </h3>
        <xsl:apply-templates select="text()"/>
    </div>
</xsl:template>

如何在XSL中检查某个部分和章节是否处于同一级别? 感谢。

3 个答案:

答案 0 :(得分:1)

如果truechapter处于同一级别,则XSLT会生成section作为其输出,否则无效:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="text" indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="*">
    <xsl:choose>
        <xsl:when test="chapter and section">true</xsl:when>
        <xsl:otherwise>
            <xsl:apply-templates select="*"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

答案 1 :(得分:0)

使用XPath轴,父类应该在这种情况下工作:

<xsl:if test="count(parent::*/*) &gt; 0">...</xsl:if>

选择父节点:parent::*

选择父节点内的所有元素节点:parent::*/*

对它们进行计数,然后检查是否为零:count(parent::*/*) > 0

*将返回任何元素节点,但不返回文本节点。您可以使用元素节点名称来选择特定的元素节点。

答案 2 :(得分:0)

您需要xsl:message

<xsl:template match="*[chapter][section]">
    <xsl:message terminate="yes">There are a section and a chapter on the same level</xsl:message>
</xsl:template>

终止=&#34;是&#34;如果处理器发出此消息,则跳过该过程。如果您只是需要警告,请切换到&#34; no&#34;。

也许Schematron对你很有兴趣。在这种情况下,您需要:

<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="xslt2">
    <pattern>
        <rule context="*[chapter]">
            <report test="section">There are a section and a chapter on the same level</report>
        </rule>
    </pattern>
</schema>