Paolo Tedesco
Paolo Tedesco

Reputation: 57172

Handling node containing inner escaped XML

I have an XML document with a node containing the escaped XML serialization of another object, as in this example:

<attribute>
  <value>
    &lt;map&gt;
      &lt;item&gt;
        &lt;src&gt;something&lt;/src&gt;
        &lt;dest&gt;something else&lt;/dest&gt;
      &lt;/item&gt;
    &lt;/map&gt;  
  </value>
</attribute>  

How can I apply an xslt template to the inner xml? In particolar, I would like to get an html table with the couples src/dest:

| src       | dest           |
| something | something else |  

Upvotes: 3

Views: 2337

Answers (2)

Tomalak
Tomalak

Reputation: 338118

I would do this as a two-step operation.

Step1.xsl:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:template match="/">
    <root>
      <xsl:apply-templates select="attribute/value" />
    </root>
  </xsl:template>

  <xsl:template match="value">
    <object>
      <xsl:value-of select="." disable-output-escaping="yes" />
    </object>
  </xsl:template>
</xsl:stylesheet>

to produce intermediary XML:

<root>
  <object>
    <map>
      <item>
        <src>something</src>
        <dest>something else</dest>
      </item>
    </map>
  </object>
</root>

Step2.xsl

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:template match="object">
    <table>
      <tr>
        <xsl:for-each select="map/item/*">
          <th>
            <xsl:value-of select="name()" />
          </th>
        </xsl:for-each>
      </tr>
      <tr>
        <xsl:for-each select="map/item/*">
          <td>
            <xsl:value-of select="." />
          </td>
        </xsl:for-each>
      </tr>
    </table>
  </xsl:template>
</xsl:stylesheet>

to produce an HTML table

<table>
  <tr>
    <th>src</th>
    <th>dest</th>
  </tr>
  <tr>
    <td>something</td>
    <td>something else</td>
  </tr>
</table>

Upvotes: 7

Oded
Oded

Reputation: 498904

Extract the value attribute into an XML document of it's own and transform that.

You will not be able to do this in a single XSLT without alot of substring replacements.

If you can control the format of the XML document, consider putting the node data into a CDATA section and not escaping the < and >.

Upvotes: 1

Related Questions