xslt

xslt convert xml string in xml elements


here's a tricky one.

I have the following XML

<test>
     <testElement SomeAttribute="<otherxml><otherElement>test test</otherElement></otherxml>">
      </testElement>
</test>

Using XSLT, I want to transform this XML to have the following result.

<test>
     <testElement>
        <SomeAttributeTransformedToElement>
          <otherxml>
               <otherElement>test test</otherElement>
          </otherxml>
        </SomeAttributeTransformedToElement>
      </testElement>
</test>

Basically, some text in an attribute must be transformed to actual elements in the final XML

Any ideas how to achieve that in XSLT?

Alex


Solution

  • You can achieve that by disabling output escaping. However, note that your input document is not a valid XML document (< is illegal in attribute values and needs escaping). I therefore changed your input document as follows:

    Input document

    <?xml version="1.0" encoding="utf-8"?>
    <test>
      <testElement SomeAttribute="&lt;otherxml>&lt;otherElement>test test&lt;/otherElement>&lt;/otherxml>">
      </testElement>
    </test>
    

    XSLT

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="@SomeAttribute">
        <SomeAttributeTransformedToElement>
          <xsl:value-of select="." disable-output-escaping="yes"/>
        </SomeAttributeTransformedToElement>
      </xsl:template>
    </xsl:stylesheet>
    

    Be aware that with disable-output-escaping="yes" there is no longer a guarantee that the produced output document is a well-formed XML document.