views:

439

answers:

1

Hello,

I am processing XML documents with JAXB 2.0 where I need information(in my example 'id') mapped to Java objects and run some business logic with. Everything works fine here.

But these XML documents always hold a collection of approximately 500 nodes that I just want to save to a database in the original xml format, so I am just interested in the XML in form of a String. In my opinion it makes no sense to unmarshal these nodes to Java objects and later on marshal them again into XML to save them into the database.

Is there any way to annotate a property and make it just hold the whole XML node as a String? Here is my current version of that class:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {

    @XmlElement(name = "id")
    public long id;

    @XmlElement(name = "child", type = String.class)
    @XmlElementWrapper(name = "children")
    public List<String> children = new ArrayList<String>();

}

After unmarshalling an XML document children.size() returns the correct number of childran but they are still null.

The XML document looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
    <id>45</id>
    <children>
        <child>
            <name>Crash Dummy</name>
            <age>21</age>
        </child>
        <child>
            <name>Rockstar Programmer</name>
            <age>12</age>
        </child>
    </children>
</parent>

Thanks in advance for every hint or a possible solution.

+1  A: 

No, JAXB does not allow something like this (nor does any other tree-based XML API that I know of).

I don't believe that the overhead for parsing the whole document will be that bad though. After all, the document needs to be parsed anyway, in order to find out where your static node tree starts and where it ends. Storing the node tree as JAXB nodes is not that much worse than having it in a large blob.

If performance is really that critical for you, I would suggest two alternatives:

  • parse the XML document using a faster API, such as StAX (getting a parser right with low-level APIs can be really difficult though)
  • store the data as two XML files. One containing the data that you actually need, and the other containing the 'static' data you just need to carry around. Depending on what you do with the final document, something like XInclude could also be used.
Tim Jansen
Hey Tim, thanks for your reply! Your argument regarding the need to parse the whole document to find the ending of the nodes that should be ignored makes sense for me! Splitting the document is no option for me since I am just the consumer of the document. I will have a look at StAX and have to compare usage and performance.
codescape