Cullub
Cullub

Reputation: 3218

Match node that might be the root

I need to match a node in xslt that might be the root element or might be a child of the root element. Is that possible?

Here's one sample file where I would need to match the Package element at the root.

<Package>
  <Target>Tablet</Target>
  <Type>DeviceApp</Type>
  <Name>MyName</Name>
  <Version>1.2.3</Version>
  <Description>My Description</Description>
  <UnneededElmt></UnneededElmt>
</Package>

<!-- Expected result: -->
<Target>Tablet</Target>
<Type>DeviceApp</Type>
<Name>MyName</Name>
<Version>1.2.3</Version>
<Description>My Description</Description>

And here's another sample where I need to match the Package element at a child level.

<testcase-root>
  <Package>
    <Target>Tablet</Target>
    <Type>DeviceApp</Type>
    <Name>MyName</Name>
    <Version>1.2.3</Version>
    <Description>My Description</Description>
    <UnneededElmt></UnneededElmt>
  </Package>
</testcase-root>

<!-- Expected result: -->
<testcase-root>
  <Target>Tablet</Target>
  <Type>DeviceApp</Type>
  <Name>MyName</Name>
  <Version>1.2.3</Version>
  <Description>My Description</Description>
</testcase-root>

For the first case, this transform does what I need:

<xsl:template match="/" >
  <xsl:copy-of select="//Package/*[not(self::UnneededElmt)]"/>
</xsl:template>

And for the second one, it works with <xsl:template match="//Package" >. But I need a match that will cover both cases (or a definitive "no, not possible" :)).

Upvotes: 0

Views: 167

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

Try it this way:

XSLT 1.0

<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="Package">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="UnneededElmt"/>

</xsl:stylesheet>

Upvotes: 3

Related Questions