在XSLT中添加缺少的XML元素需要什么?
发布时间:2020-12-16 23:06:28 所属栏目:百科 来源:网络整理
导读:我正在尝试将 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 <?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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |