简体   繁体   中英

Stripping all elements except one in XML using XSLT

I would like to remove all elements from XML except content of element called <source>. Eg:

<root>
 <a>This will be stripped off</a>
 <source>But this not</source>
</root>

After XSLT:

But this not

I have tried this but with no luck (no output):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="source">
      <xsl:copy>
         <xsl:apply-templates select="node()"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">

</xsl:stylesheet>

From comments :

In my real XML I have the source element in different namespace. I need to google how to create a match pattern for element in different namespace. I would like to put each extracted string also to newline ;-)

You're not far off. The reason you're not getting any output is because your root match-all template isn't recursing but just terminating so you need to put an apply-templates call inside it. The following stylesheet gives the expected output.

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text"/>

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

    <xsl:template match="source">
        <xsl:value-of select="text()"/>
    </xsl:template>

</xsl:stylesheet>

Note that I've changed the output mode to text and the source template to simply output the textual value of the node, because it looks like you want text and not XML output.

Just for fun, the sortest solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ex="http://example.org">
    <xsl:output method="text"/>
    <xsl:template match="text()"/>
    <xsl:template match="ex:source">
        <xsl:value-of select="concat(.,'&#xA;')"/>
    </xsl:template>
</xsl:stylesheet>

With this input:

<root xmlns="http://example.org">
    <a>This will be stripped off</a>
    <source>But this not</source>
</root>

Output:

But this not

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