输入XML
<Web-inf>
<A>
<A1>Val1</A1>
<A1>Val1</A1>
<A1>Val1</A1>
</A>
<A>
<A1>Val2</A1>
<A1>Val2</A1>
<A1>Val2</A1>
</A>
<B>
<B1>Hi</B1>
</B>
<B>
<B1>Bye</B1>
</B>
<C>DummyC</C>
<D>DummyD</D>
</Web-inf>
我想添加<B>
标记,如果它已经不存在<B1>
值为&#34;早晨&#34;和&#34;晚上&#34;。如果它存在我就什么都不做。我写了下面的转换,但奇怪的是只有LATER一个工作,第一个被完全忽略。因此,仅<B><B1>Evening</B1></B>
仅与<B>
标记一起插入。这是一个已知问题吗?如果是,请如何纠正?
<xsl:output method="xml" indent="yes" />
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Web-inf[not(B[B1='Morning'])]/B[last()]">
<xsl:copy-of select="*" />
<B>
<B1>Morning</B1>
</B>
</xsl:template>
<xsl:template match="Web-inf[not(B[B1='Evening'])]/B[last()]">
<xsl:copy-of select="*" />
<B>
<B1>Evening</B1>
</B>
</xsl:template>
我希望O / P XML如下所示
的Output.xml
<Web-inf>
<A>
<A1>Val1</A1>
<A1>Val1</A1>
<A1>Val1</A1>
</A>
<A>
<A1>Val2</A1>
<A1>Val2</A1>
<A1>Val2</A1>
</A>
<B>
<B1>Hi</B1>
</B>
<B>
<B1>Bye</B1>
</B>
<B>
<B1>Morning</B1>
</B>
<B>
<B1>Evening</B1>
</B>
<C>DummyC</C>
<D>DummyD</D>
</Web-inf>
答案 0 :(得分:1)
对于您输入的XML,B[last()]
的两个模板都将匹配。当两个模板匹配具有相同优先级的元素时,这被视为错误。 XSLT处理器将标记错误,或忽略除最后一个匹配模板之外的所有模板。
在这种情况下,单个模板匹配xsl:if
可能更好,并且模板中的其他条件为<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Web-inf/B[last()]">
<xsl:copy-of select="*" />
<xsl:if test="not(../B[B1='Morning'])">
<B>
<B1>Morning</B1>
</B>
</xsl:if>
<xsl:if test="not(../B[B1='Evening'])">
<B>
<B1>Evening</B1>
</B>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
语句。
试试这个XSLT
Person person = em.find(Person.class, p);