Xpath Predicate to match <![CDATA[sometext]]>

2019-08-20 14:07发布

My xml element content is having special characters like <,>,[,]. I want to find element macthing the content <![CDATA[someText]]>and replace it with some new value like <![CDATA[newValue]]>.

<property name="sourcePath">
    <string><![CDATA[someText]]></string>
</property>`

I am trying to do this using below xsl template. But it is not working.

<xsl:template match="property[string='<![CDATA[someText]]>']">    
   <xsl:element name="string">                 
                <xsl:text disable-output-escaping="yes">&lt;![CDATA[newValue]]&gt;</xsl:text>
</xsl:element>        

Please help.

1条回答
可以哭但决不认输i
2楼-- · 2019-08-20 14:44

A CDATA section is not presereved in the XML INFOSET, so its contents is just regular text -- a complete text node or a part of a text node.

In your case the CDATA section is the complete text node, so you can have:

<xsl:template match="property[string='someEscapedText']">
  <string>newEscapedValue</string>
</xsl:template>

You don't need to use DOE or CDATA -- just escape the characters in NewValue and use the cdata-section-elements="string" attribute of the <xsl:output> declaration.

And here is the complete solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
 <xsl:output cdata-section-elements="string"
  omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match=
  "property[string='&lt;p>Hello, World&lt;/p>']">
   <string>&lt;p>Hello, You&lt;/p></string>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<property>
 <string><![CDATA[<p>Hello, World</p>]]></string>
</property>

the wanted, correct result is produced:

<string><![CDATA[<p>Hello, You</p>]]></string>
查看更多
登录 后发表回答