我是XSL的新手,我正在尝试使用以下结构压缩XML文件,目的是在InDesign中使用它(真正的XML结构要复杂得多,实际上遵循NLM模式,但下面的示例应该努力说明我的需要):
实施例
<section>
<p> just normal text here 1</p>
<section>
<p>just normal text for this section</p>
</section>
<p>just normal text here 2</p>
<section>
<p>just more text</p>
<section>
<p>this is the text in the deepest section </p>
</section>
<p>and even more text </p>
</section>
<p>just normal text here 3</p>
</section>
我几乎完成了以下XSLT所需的工作:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="section">
<xsl:variable name="sectionlevel">
<xsl:value-of select="count(ancestor::section)" />
</xsl:variable>
<xsl:element name="s{$sectionlevel}">
<xsl:apply-templates select="descendant::section" />
<xsl:copy-of select="*[local-name() != 'section']"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
我使用此代码获得的输出是下面显示的那个很好,但问题是我需要保持元素的顺序。我只需要更改节元素名称并保持其他所有内容相同:
<?xml version="1.0" encoding="utf-8"?>
<s0>
<s1>
<p> just normal text for this section</p>
</s1>
<s1>
<s2>
<p>this is the text in the deepest section </p>
</s2>
<p>just more text</p>
<p>and even more text </p>
</s1>
<s2>
<p>this is the text in the deepest section </p>
</s2>
<p> just normal text here 1</p>
<p>just normal text here 2</p>
<p>just normal text here 3</p>
</s0>
正如您所看到的,此示例中的
元素被移动到section元素内的末尾。我应该如何编写XSL转换代码,以便保留所有原始XML顺序和结构,只更改部分标签?
答案 0 :(得分:2)
这是你期望的吗?
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<!-- Identity to copy all elements -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="section" >
<xsl:element name="s{count(ancestor::section)}">
<xsl:apply-templates select="@*|node()" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
这将输出:
<?xml version="1.0" encoding="UTF-8"?>
<s0>
<p> just normal text here 1</p>
<s1>
<p>just normal text for this section</p>
</s1>
<p>just normal text here 2</p>
<s1>
<p>just more text</p>
<s2>
<p>this is the text in the deepest section </p>
</s2>
<p>and even more text </p>
</s1>
<p>just normal text here 3</p>
</s0>