I have an XML document, and I want to change the values for one of the attributes.
First I copied everything from input to output using:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
And now I want to change the value of the attribute "type"
in any element named "property"
.
I also came across same issue and i solved it as follows:
For the following XML:
I was able to get it to work with the following XSLT:
Tested on a simple example, works fine:
Edited to include Tomalak's suggestion.
If your source XML document has its own namespace, you need to declare the namespace in your stylesheet, assign it a prefix, and use that prefix when referring to the elements of the source XML - for example:
Or, if you prefer:
ADDENDUM: In the highly unlikely case where the XML namespace is not known beforehand, you could do:
Of course, it's very difficult to imagine a scenario where you would know in advance that the source XML document contains an element named "property", with an attribute named "type" that needs replacing - but still not know the namespace of the document. I have added this mainly to show how your own solution could be streamlined.
This problem has a classical solution: Using and overriding the identity template is one of the most fundamental and powerful XSLT design patterns:
When applied on this XML document:
the wanted result is produced:
You need a template that will match your target attribute, and nothing else.
This is in addition to the "copy all" you already have (and is actually always present by default in XSLT). Having a more specific match it will be used in preference.