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

心已入冬 提交于 2020-01-17 01:19:20

问题


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:


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>


来源:https://stackoverflow.com/questions/4522226/xpath-predicate-to-match-cdatasometext

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