Anna Morning
Anna Morning

Reputation: 632

XSLT Removing element with attribute but keep the children

I need to transform xml/html files into dita files. I want to remove some nodes but keep their children. The difficulties are:

  1. Node I want to remove have attributes. I get error:

    An attribute node (class) cannot be created after a child of the containing element

  2. And these attributes are unpredictable: I want to remove a variety of nodes, and I can't predict what kinds of attributes they have.

  3. I don't know how deeply the node is nested in. It could be direct child of <body> or could be nested 4 or 5 levels down inside some other nodes.

XML Example:

<macro name="section">
   <rich-text-body>
      <macro name="column">
         <parameter name="width">80%</parameter>
         <rich-text-body>
            <p>horribly nested, <span>bulky</span> structure</p>
            <div>horribly nested, <span>bulky</span> structure</div>
         </rich-text-body>
      </macro>
   </rich-text-body>
</macro>

I want to remove the bulky macro tags, but keep only the children of the most inner <rich-text-body>. In this case, they are the <p> <div> tags.

This is as far as I got. The XSLT

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

<xsl:template match="macro[@name='column' and parameter[@name='width'] ='80%']">
    <xsl:apply-templates select="node()|@*"/>
</xsl:template>

Any help is appreciated! Thanks!

Upvotes: 0

Views: 2324

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

As already suggested, if you change

<xsl:template match="macro[@name='column' and parameter[@name='width'] ='80%']">
    <xsl:apply-templates select="node()|@*"/>
</xsl:template>

to

<xsl:template match="macro[@name='column' and parameter[@name='width'] ='80%']">
    <xsl:apply-templates select="node()"/>
</xsl:template>

respectively the equivalent but shorter

<xsl:template match="macro[@name='column' and parameter[@name='width'] ='80%']">
    <xsl:apply-templates/>
</xsl:template>

then you won't get any errors from the attributes of the macro element as they are not processed.

If you want to process them to add them to a different element then you need to show us exactly where you want to put them.

Upvotes: 1

Related Questions