Manas
Manas

Reputation: 43

How to write an xslt on a xml which contains < > instead of '<' and '>'

For example I am calling a web service which gives me the following response:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Header/>
    <soapenv:Body>
        <executeResponse>
            <executeReturn>
                &lt;Message&gt;
                    &lt;Body&gt;
                        &lt;Clients&gt;
                            &lt;Client&gt;
                                &lt;ClientID&gt;C000001&lt;/ClientID&gt;
                            &lt;/Client&gt;
                            &lt;Client&gt;
                                &lt;ClientID&gt;C000002&lt;/ClientID&gt;
                            &lt;/Client&gt;
                        &lt;/Clients&gt;
                    &lt;/Body&gt;
                &lt;/Message&gt;
            </executeReturn>
        <executeResponse>
    </soapenv:Body>
</soapenv:Envelope>

How to write an XSLT so that I can transform the response to this:

<Customers>
    <Customer>
        <CustomerID>C000001<CustomerID>
        <CustomerID>C000002<CustomerID>
    <Customer>
<Customers>

Upvotes: 2

Views: 193

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167401

If you have access to an XSLT 3 processor like Saxon 9.8 you can use the parse-xml function to parse the escaped markup into XML nodes and then you can transform them so

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:mode on-no-match="text-only-copy"/>

  <xsl:template match="executeReturn">
      <xsl:apply-templates select="parse-xml(.)"/>
  </xsl:template>

  <xsl:template match="Clients">
      <Customers>
          <Customer>
              <xsl:apply-templates/>
          </Customer>
      </Customers>
  </xsl:template>

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

</xsl:stylesheet>

transforms your input at https://xsltfiddle.liberty-development.net/eiZQaF2 into

<?xml version="1.0" encoding="UTF-8"?>
<Customers>
   <Customer>
      <CustomerID>C000001</CustomerID>
      <CustomerID>C000002</CustomerID>
   </Customer>
</Customers>

With earlier versions of XSLT you need to check whether your processor provides an extension function or allows you to implement one or you need to write two XSLT stylesheets where the first outputs the escaped markup using disable-output-escaping and the second then transforms that output of the first.

Upvotes: 2

Related Questions