是否有可能根据处理指令设置属性。我们使用的是XLST 1.0,我有以下XML文件:
<body>
<div>
Text
</div>
<div>
<?class-start type="blue" ?>
<span>
<div>
Text1
</div>
</span>
<?class-end type="blue" ?>
</div>
<div>
<?class-start type="green" ?>
<span>
<div>
<?class-end type="green" ?>
Text2
</div>
</span>
</div>
<div>
<span>
<?class-start type="red" ?>
<div>
Text3
</div>
<div>
Text4
</div>
<div>
Text5
</div>
<div>
Text6
</div>
<?class-end type="red" ?>
</span>
</div>
</body>
我想把它转换成以下XML文件:
<body>
<div>
Text
</div>
<div>
<span class="blue">
<div class="blue">
Text1
</div>
</span>
</div>
<div>
<?class-start type="green" ?>
<span class="green">
<?class-end type="green" ?>
<div>
Text2
</div>
</span>
</div>
<div>
<span>
<div class="red">
Text3
</div>
<div class="red">
Text4
</div>
<div class="red">
Text5
</div>
<div class="red">
Text6
</div>
</span>
</div>
</body>
是否有可能像使用XSLT 1.0那样转换它,或者我应该使用一个小程序(Java或其他东西)来转换它?
谢谢!
这不是很有效,而且还假设您没有重叠的class-start
和class-end
处理指令,但是这里有一种方法可以在XSLT 1.0
<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="*[count(preceding::processing-instruction('class-start')) = count(preceding::processing-instruction('class-end')) + 1]">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:attribute name="class">
<xsl:value-of select="normalize-space(translate(substring-after(preceding::processing-instruction('class-start')[1], '='), '"', ''))" />
</xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="processing-instruction('class-start')|processing-instruction('class-end')" />
</xsl:stylesheet>