简体   繁体   中英

Processing XML inside XML text node with XSLT

I have an XML with a text node that is also an XML. I need to transform this XML (the outer XML) with XSLT 2.0 and change a couple of things in the inner XML (the one in the text node). The result XML should have the same structure as the input XML (including the text node with XML), but with the changes applied on the inner XML.

I'm using Saxon XSLT processor, so I have access to the parse() function. But I'm not sure how I can use it to process the inner XML and then convert it back to a text node.

This is a sample input XML:

<tag>
    <innerXml>
         &lt;node1&gt;
           &lt;node2&gt;Value&lt;/node2&gt;
         &lt;/node1&gt;
    </innerXml>
</tag>

And the XSLT transform would output:

<tag>
    <innerXml>
         &lt;node1&gt;
           &lt;node2&gt;Some other value&lt;/node2&gt;
         &lt;/node1&gt;
    </innerXml>
</tag>

Note that the inner XML is much more complex than this, so a simple string replace won't work.

Well you should be able to do (where you have xmlns:saxon="http://saxon.sf.net/" )

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:saxon="http://saxon.sf.net/"
  xmlns:my="http://example.com/my"
  exclude-result-prefixes="saxon my"

  version="2.0">

<xsl:output name="my:ser" method="xml" omit-xml-declaration="yes"/>

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

<xsl:template match="innerXml">
  <xsl:variable name="temp">
    <xsl:apply-templates select="saxon:parse(.)/node1"/>
  </xsl:variable>
  <xsl:copy>
   <xsl:value-of select="saxon:serialize($temp, 'my:ser')"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="node2[. = 'Value']">
  <xsl:copy>
    <xsl:text>Some other value</xsl:text>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Tested with Saxon 9.1. And with the commercial versions of Saxon 9.3 you could alternatively use version="3.0" for the stylesheet and that way use the built-in parse and serialize functions in the default function namespace instead of using the Saxon extension functions I used above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM