Matt Broekhuis
Matt Broekhuis

Reputation: 2075

Jax-b serialization of literal xml

I have a pojo, which is annotated with JAX-B annotations. I use the setters and getters to populate the object. I use the marshaller to write out the xml to a document, which eventually is written by another api to an outputstream.

Object o = new Object('blah','blah','blah');
Document doc = db.newDocument();
marshaller.marshal(o, doc);

however, I have a string of xml that I need to set as an attribute on one of my pojo fields, but I need it to be marshalled as xml, not as a string. It is xhtml, so I know the format. How can I go about doing this? I do have an xsd, but obviously there is no "type" for xml.

//need to do this
String xml = <tag>hello</tag>;
Object o = new Object('blah','blah','blah');
o.setThisXmlField(xml);
marshaller.marshal(o, doc);

edit--> this is how I accomplished this

 <xs:element name="course">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="courseSummary" type="courseSummary"/> 
        </xs:sequence>
     </xs:complexType>
  </xs:element> 

<xs:complexType name="courseSummary">
    <xs:sequence>
        <xs:any/>
    </xs:sequence>
</xs:complexType>

And the generated java code is used like:

Tidy tidy = new Tidy();
tidy.setXHTML(true);
String courseSummary = "some turruble xml <b>REALLY RUBBISH</li>";
Course c = new Course();
Document courseSummaryDoc = tidy.parseDOM(IOUtils.toInputStream(courseSummary),null);
CourseSummary summary = new CourseSummary();
summary.setAny(courseSummaryDoc.getDocumentElement());
c.setCourseSummary(summary);

Upvotes: 2

Views: 247

Answers (2)

Petru Gardea
Petru Gardea

Reputation: 21658

I would probably modify the XML Schema used to describe your content model to allow for an xsd:any where you wish to inject your xhtml content. You can restrict the xsd:any to match only the XHTML namespace, if you wish to further restrict the allowed elements at that location.

You would then simply have to follow the xsd:any on JAXB implementation rules and the output will be sent as XML.

If you don't start from an XSD, then the above link also shows the annotation you need to use to describe the equivalent of the xsd:any.

@XmlAnyElement
public List<Element> getAny();

where Element is org.w3c.dom.Element.

Upvotes: 3

Chris
Chris

Reputation: 23179

Your best bet is probably to enclose the content of your xml tag in a CDATA block. You can do that by configuring the OutputFormat for JaxB:

OutputFormat of = new OutputFormat();
of.setCDataElements(new String[] { "thisXmlField"});
XMLSerializer serializer = new XMLSerializer(of);
marshaller.marshal(o, serializer.asContentHandler());

Upvotes: 1

Related Questions