我正在尝试将XML文件转换为另一个XML文件,并在未提供内容的情况下添加额外内容。
我的XML看起来像这样:
<bookstore>
<book>
<title>Book1</title>
<author>Author1</author>
<chapters>
<chapter>
<ch-name>BLABLA</ch-name>
<ch-number>1</ch-number>
</chapter>
</chapters>
</book>
<book>
<title>Book2</title>
<author>Author2</author>
<chapters>
<chapter>
<ch-name>Test</ch-name>
<ch-number>1</ch-number>
</chapter>
</chapters>
</book>
<book>
<title>Book3</title>
<author>Author3</author>
</book>
</bookstore>
现在,我想将章节元素(及其子元素)添加到已经不存在的书籍中,以创建某种默认值。
我的XSLT看起来像这样:
<dns:template match="book[not(exists(chapters))]">
<xsl:copy>
<xsl:apply-templates select="@*|*"/>
</xsl:copy>
<chapters>
<chapter>
<ch-name>default</ch-name>
<ch-number>default</ch-number>
</chapter>
</chapters>
</dns:template>
<xsl:template match="@* | *">
<xsl:copy>
<xsl:apply-templates select="@* | * | text()"/>
</xsl:copy>
</xsl:template>
但是,当我在在线编辑器中尝试此操作时,没有任何更改。 dns名称空间应该支持not(exists)部分。
我的XSLT有问题吗?
感谢您提供任何帮助!
答案 0 :(得分:2)
将“dns”前缀更改为“xsl”(当然,您可以使用相同的命名空间再次定义前缀,但不建议这样做)。如果您使用的是XSLT1.0,则不存在“exists()”函数。 此外,“章节”需要在里面。 你可以使用这个xslt:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="book[not(chapters)]">
<xsl:copy>
<xsl:apply-templates select="@*|*"/>
<chapters>
<chapter>
<ch-name>default</ch-name>
<ch-number>default</ch-number>
</chapter>
</chapters>
</xsl:copy>
</xsl:template>
<xsl:template match="@* | *">
<xsl:copy>
<xsl:apply-templates select="@* | * | text()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>