I'm trying to convert a third party xml using an xsl transformation and then converting the resultant xml to a java object with JAXB. But some where in between an element content marked as CDATA gets lost.
Here is my sample thirdparty xml
<person>
<name>aName</name>
</person>
XSL transformation
<xsl:template match="/">
<User>
<personName><xsl:value-of select="//name"/></personName>
<!-- Saving input xml as CDATA for future ref -->
<inputXml>
<xsl:text disable-output-escaping="yes"><![CDATA[</xsl:text>
<xsl:copy-of select="."/>
<xsl:text disable-output-escaping="yes">]]></xsl:text>
</inputXml>
</User>
</xsl:template>
Java Class
@XmlRootElement
public class User{
@XmlElement
public String personName;
@XmlElement
public String inputXml
}
Translation
JAXBResult jaxbResult = new JAXBResult(JAXBContext.newInstance(User.class));
newXslTransformer().transform(new StreamSource(thirdPatyXmlFile), jaxbOutput);
User user = (User)jaxbResult.getResult();
System.out.println(user.inputXml);
But the above code outputs the inputXml as ]]>. I'm able to get the inputXml if I hard-coded the CDATA as below, but not when I generate it dynamically.
<inputXml><![CDATA[<person><name>aName</name></person>]]></inputXml>
Any suggestions would be greatly appreciated.
A JAXBResult
is a SAXResult
therefore the transformation result is issued as series of SAX events and a JAXB unmarshaller uses them to construct your User
object.
This is an effective technique to avoid writing the transformation and reparsing later when you unmarshal.
Unfortunately your CDATA hack does not go well with this.
Within <inputXml>
the ContentHandler of the JAXBResult sees text "<![CDATA["
, then your whole input document as a series of element and text events, then the closing text event "]]>"
- and the last one is used as value for User.inputXml
.
Seems that you need to transform to a memory buffer and then unmarshal from that.