Replacing all matching nodes in XML using XSLT

217 Views Asked by At

I wanted to replace all matching nodes in the xml-file.

To the original xml:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel>
    <Button/>
  </StackPanel>
</Window>

I applied the following xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Button">
        <AnotherButton><xsl:apply-templates select="@*|node()" /></AnotherButton>
    </xsl:template>    
</xsl:stylesheet>

But it produces the same xml. What I did wrong?

1

There are 1 best solutions below

0
On

What Sean is saying is that if you remove the namespace from your XML document the XSLT will work

<Window>
  <StackPanel>
    <Button/>
  </StackPanel>
</Window>

produces...

<Window>
    <StackPanel>
        <AnotherButton />
    </StackPanel>
</Window>

Alternatively, you asked if you can keep your namespace

Add your x: namespace to your Button...

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel>
    <x:Button/>
  </StackPanel>
</Window>

Update your XSL to also use this x:Button namespace

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="x:Button">
        <x:AnotherButton><xsl:apply-templates select="@*|node()" /></x:AnotherButton>
    </xsl:template>    
</xsl:stylesheet>

produces...

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <x:AnotherButton/>
    </StackPanel>
</Window>