我有以下xml
文件
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:t="http://www.tibco.com/xmlns/ApplicationManagement"
name="test">
<content>
<on> false </on>
</content>
</application>
我想让我的xsl
修改xml
以便:
如果确实存在具有相同名称的标记,则覆盖该值。
如果不存在具有相同值的标签,则将其插入。
这是我的xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:t="http://www.tibco.com/xmlns/ApplicationManagement"
xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output encoding="UTF-8" indent="yes" method="xml"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="content">
<xsl:copy>
<xsl:apply-templates/>
<xsl:if test="not(status)">
<status>new status </status>
</xsl:if>
<xsl:if test="on">
<on>new on value</on>
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
我在<on>new on value</on>
上遇到了问题,因为解决方案应该替换on
标签值,而是创建一个全新的
结果如下(没有顶部 xml 和应用程序标记(:
<content>
<on> false </on>
<value> light </value>
<status xmlns="http://www.w3.org/1999/xhtml">new status
</status>
<on xmlns="http://www.w3.org/1999/xhtml">new on value
</on>
</content>
如何替换同一模板中的 on 标签?
您可以使用
模板匹配来匹配<on>
元素和<status>
元素(不是示例的一部分(。
<xsl:template match="content"> <!-- remove <xsl:if...> from this template -->
<xsl:copy>
<xsl:apply-templates />
<xsl:if test="not(status)"> <!-- if <status> element does not exist, create one -->
<status>added new status </status>
</xsl:if>
<xsl:if test="not(on)"> <!-- if <on> element does not exist, create one -->
<on>added new on value</on>
</xsl:if>
</xsl:copy>
</xsl:template>
<xsl:template match="on[parent::content]"> <!-- replaces <on> elements with parent <content> -->
<on>new on value</on>
</xsl:template>
<xsl:template match="status[parent::content]"> <!-- replaces <status> elements with parent <content> -->
<status>new status </status>
</xsl:template>
输出:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:t="http://www.tibco.com/xmlns/ApplicationManagement" name="test">
<content>
<on xmlns="http://www.w3.org/1999/xhtml">new on value</on>
<status xmlns="http://www.w3.org/1999/xhtml">added new status </status>
</content>
</application>