我正在尝试将 XML文件转换为更新版本. 我有以下源XML ?xml version="1.0" encoding="utf-8" ?config section name="abc" key name="key1"My Key One/key /section section name="def" key name="key2"My Key Two/key /section/config 转换
我有以下源XML
<?xml version="1.0" encoding="utf-8" ?>
<config>
<section name="abc">
<key name="key1">My Key One</key>
</section>
<section name="def">
<key name="key2">My Key Two</key>
</section>
</config>
转换看起来像这样……但是,目标实际上可能看起来像这样,所以我不希望添加部分xyz如果已经存在:
<?xml version="1.0" encoding="utf-8" ?>
<config>
<section name="abc">
<key name="key1">My Key One</key>
</section>
<section name="def">
<key name="key2">My Key Two</key>
</section>
<section name="xyz">
<key name="key3">My Key Three</key>
</section>
</config>
XSLT目前看起来像这样:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="config"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|text()|comment()|processing-instruction()"> <xsl:copy-of select="."/> </xsl:template> <xsl:template match="config/section"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="config/section/key"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
这似乎复制了存在的东西.如果它实际上丢失了,如何添加我缺少的元素呢?
尝试这样的事情:<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="config">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
<xsl:if test="not(section/@name='xyz')">
<section name="xyz">
<key name="key3">My Key Three</key>
</section>
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
