我是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>
通过此代码获得的输出如下所示,这很好,但问题是我需要保持元素的顺序。我只需要更改section元素名称,并保持其他所有内容不变:
<?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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句