它我有一个源文件:XSLT插入元素,如果不存在
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id='MatchId' />
</source>
和含内容样式表我要代入来源:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" omit-xml-declaration="no" version="1.0"/>
<xsl:preserve-space elements="//*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="ItemToBeSubstituted[@Id = 'MatchId']">
<xsl:copy>
<xsl:copy-of select="@*|*"/>
<Element1/>
<Element2 Value="foo"/>
<Element3 Value="bar"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这个样式表succesfuly副本<Element1/><Element2 Value="foo"/><Element3 Value="bar"/>
分成ItemToBeSubstituted
。但是,当我使用不同的源文件,其中ItemToBeSubstituted
已经有内容:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id='MatchId'>
<Element3 Value="baz"/>
</ItemToBeSubstituted>
</source>
我得到这样的输出:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id="MatchId">
<Element3 Value="baz"/>
<Element1/>
<Element2 Value="foo"/>
<Element3 Value="bar"/>
</ItemToBeSubstituted>
</source>
我想唯一的替代者从不存在的样式表元素在源文件中。这是应用样式到第二个文档后,我在寻找的输出,只有从源文件的<Element3>
元素:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id="MatchId">
<Element3 Value="baz"/>
<Element1/>
<Element2 Value="foo"/>
</ItemToBeSubstituted>
</source>
什么是与XSL这样做的最佳方法?样式表可能包含许多要替换的元素。所以我不想用一种方法,每个单元都需要一个<xsl:if>
。有没有更好的方法比使用一个样式表插入内容,然后有第二个样式表删除重复的元素?
+1这是问题的良好开端。它可以使用一个更普遍的事实,显然可能有更多的元素被替换为比ItemToBeSubstituted [@Id ='MatchId']`,但这不是很难做到。 – Tomalak 2009-08-05 09:45:14