Reputation: 4787
I have the following xml
file
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:t="http://www.tibco.com/xmlns/ApplicationManagement"
name="test">
<content>
<on> false </on>
</content>
</application>
I want to have my xsl
modify the xml
so that:
If a tag does exist with the same name, then overwrite the value.
If a tag does not exist with the same value, then insert it in.
Here is my 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>
I am having problems with the <on>new on value</on>
, as the solution should replace the on
tag value, but instead creates an entirely new one
The result is the following (without the top xml and application tags):
<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>
How can I replace the on tag, in the same template?
Upvotes: 0
Views: 372
Reputation: 29052
You can use template matching to match the <on>
element and the <status>
element (not part of the example).
<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>
Output:
<?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>
Upvotes: 2