我是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 顺序和结构并仅更改节标签?
这是你所期望的吗?
<?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>