Domanda

I am new to XSLT and working on transformation from one XML to another and facing below issue

If Book 1 node exist then I should not see Book 2 node into transformed XML. I tried different phrases but doesn't work.

Input XML

<?xml version="1.0" encoding="UTF-8"?>
<Catalog>
  <book1>Wise Otherwise</book1>
  <book2>Great Expectations</book2>>
</Catalog>

Expected XML Wise Otherwise

Below is my XSL

<?xml version="1.0" encoding="UTF-8"?>

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

<xsl:if test="book1">
    <xsl:template match="book2" />
</xsl:if>

<xsl:if test="not(book1)">
    <xsl:template match="book2">
    <book2>
        <xsl:apply-templates />
    </book2>
</xsl:template>
</xsl:if>   
</xsl:stylesheet>

I even tried xsl:Choose

<xsl:choose>
<xsl:when test="/catalog/book1">
     <xsl:template match="book2" />
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
     <xsl:template match="book2">
    <book2>
        <xsl:apply-templates />
    </book2>
    </xsl:template>
</xsl:otherwise>
</xsl:choose>

Book1 and Book2 are mutual exclusion from transformed xml.

Book2 should be in transformed XML if and only if Book1 is not in input XML.

I hope this will give you better picture

Thanks

È stato utile?

Soluzione

Use a stylesheet with the identity transformation template

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

and the template <xsl:template match="Catalog[Book-1]/Book-2"/>.

Based on your provided XML sample a complete XSLT stylesheet is

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

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

<xsl:template match="Catalog[book1]/book2"/>

</xsl:stylesheet>

which transforms

<Catalog>
  <book1>Wise Otherwise</book1>
  <book2>Great Expectations</book2>
</Catalog>

into

<Catalog>
  <book1>Wise Otherwise</book1>

</Catalog>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top