Handling node containing inner escaped XML

随声附和 提交于 2019-12-10 18:44:48

问题


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 |  

回答1:


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>



回答2:


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 >.



来源:https://stackoverflow.com/questions/1927522/handling-node-containing-inner-escaped-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!