marOne
marOne

Reputation: 149

XSLT: Exclude an element but keep it's sub elements

Hi I want to exclude a specific element, in this case <ph> and keep it's sub elements. xml file:

<?xml version="1.0" encoding="UTF-8"?>
<p>
   <s>
      <ph>
         <w>this</w>
         <w>is</w>
         <w>my</w>
         <w>first</w>
         <w>sentence</w>
         <pc>.</pc>
      </ph>
   </s>
   <s>
      <ph>
         <w>this</w>
         <w>is</w>
         <w>my</w>
         <w>second</w>
         <w>sentence</w>
         <pc>.</pc>
      </ph>
   </s>
</p>

desired output:

<?xml version="1.0" encoding="UTF-8"?>
<p>
   <s>
      <w>this</w>
      <w>is</w>
      <w>my</w>
      <w>first</w>
      <w>sentence</w>
      <pc>.</pc>
   </s>
   <s>
      <w>this</w>
      <w>is</w>
      <w>my</w>
      <w>second</w>
      <w>sentence</w>
      <pc>.</pc>
   </s>
</p>

xsl code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
<xsl:template match="p|s|w|pc">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:copy-of select="p|s|w|pc"/>
            <xsl:apply-templates select="*/*[not(self::phr)]"/> 
        </xsl:copy> 
    </xsl:template>
</xsl:stylesheet>

The problem is that sometimes when <ph> is not there I lose sub elements, or have the same xml file with the <ph> element.

Upvotes: 0

Views: 414

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117043

How about:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="ph">
    <xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>

Upvotes: 4

Related Questions