开发者

JAXB 2.0 - How to skip processing of nodes and return them as a String

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 {

    @开发者_JS百科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.


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜