简体   繁体   中英

Replacing all matching nodes in XML using XSLT

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM