我有一个源文件:
<?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>
此样式表已成功复制<Element1/><Element2 Value="foo"/><Element3 Value="bar"/>
into 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>
围绕每一个元素。有没有比使用一个样式表插入内容,然后使用第二个样式表删除重复元素更好的方法?