0

I have an application that reads and writes data from/to XML files to/from a DB using JAXB. The "human readability" of these XML files is one of the top priorities in this project as the idea is that XML files from different DBs can be compared to each other.

Now, I have some tables with attributes that hold XML strings themselves which need to be included to my JAXB objects. As I don't have control over these XML strings and readability is key, I helped myself so far with an XmlAdapter that pretty prints the XML from the DB and wraps it in a CDATA element.

The problem of this solution is that the XML string looks a bit lost within the CDATA element and smart text editors with syntax highlighting don't recognize the XML, so they don't highlight the syntax of that XML.

I was wondering therefore if there's a way to "embed" this XML within an element of my JAXB model as if it would be part of the model. So, I need a kind of XmlAdapter that would parse an XML from a String field of my JAXB class and somehow pass the parsing events to the underlying XMLWriter.

I've spent a lot of time looking for a solution combining JAXB and Stax but didn't succeed. In my view I would need some hook exactly between the JAXB and the Stax layer, so that I can customize the events that JAXB sends to the Stax Writers.

Example:

@XmlRootElement
public class MyJaxbModel {

  @XmlAttribute
  private Integer anAttribute;
  @XmlElement
  private String xml;

  public MyJaxbModel(Integer anAttribute, String xml) {
    this.anAttribute = anAttribute;
    this.xml = xml;
  }

  ...
}

Then marshalling the following instance of this class

new MyJaxbModel(999, "<?xml version=\"1.0\" encoding=\"UTF-8\"?><element1><child1>bla</child1><child2>ble</child2></element1>");

should result in the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<MyJaxbModel anAttribute="999">
   <xml>
      <element1>
        <child1>bla</child1>
        <child2>ble</child2>
      </element1>
   </xml>
</MyJaxbModel>

Obviously I need it to work also the other way round, i. e. unmarshalling this XML would return me the MyJaxbModel object including the XML string in the xml field.

Alex
  • 1,126
  • 1
  • 11
  • 24
  • how about using `xsd:anyType` for your `` element? I guess, then you can assign any xml in it. As I remember in JAXB it will be just `java.lang.Object`, but if you do not care to process it in your code it could be what you need... – Vadim Aug 25 '17 at 22:39
  • Thanks, that does look promising and guided me to [this post](https://stackoverflow.com/questions/13941747/serializing-with-jaxb-and-the-any). I'll give it a try and post the solution if it works. – Alex Aug 28 '17 at 12:36

0 Answers0