java: remove cdata tag from xml

SandyBr picture SandyBr · Jul 26, 2011 · Viewed 13.1k times · Source

xpath is nice for parsing xml files, but its not working for data inside the cdata tag:

<![CDATA[ Some Text <p>more text and tags</p>... ]]>

My solution: Get the content of the xml first and remove

"<![CDATA["  and  "]]>".

After that I would run xpath "to reach everything" from the xml file. Is there a better solution? If not, how can I do it with a regular expression?

Answer

Paŭlo Ebermann picture Paŭlo Ebermann · Jul 27, 2011

The reason for the CDATA tags there is that everything inside them is pure text, nothing which should be interpreted directly as XML. You could write your document fragment in the question alternatively as

 Some Text &lt;p&gt;more text and tags&lt;/p&gt;... 

(with a leading and trailing space).

If you really want to interpret this as XML, extract the text from your document, and submit it to an XML parser again.