Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm parsing an XML document that has nodes like the following:

<objects>
  <dog>
    <data1>...</data1>
    <data2>...</data2>
    <data3>...</data3>
  </dog>
  <cat>
    <data1>...</data1>
    <data2>...</data2>
    <data3>...</data3>
  </cat>
</objects>

The elements data1, data2, data3 are always consistent. Only the parent tag varies. In my object model I have a single Object which represents all of these cases. How can I get JAXB to handle this case without knowing in advance the name of the element?

@XMLAnyElement matches all the objects but doesn't create an object of the appropriate type; I get a list of Node objects instead of my object. My object currently looks something like:

public class MyObject {
    protected String otherData;

    @XmlAnyElement
    @XmlElementWrapper(name = "objects")
    protected List<MyChildObject> childObjects;
}

public class MyChildObject {
    protected String data1;
    protected String data2;
    protected String data3;
}

Any ideas how to handle this case short of changing the incoming XML format to use <object type="dog"> elements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
246 views
Welcome To Ask or Share your Answers For Others

1 Answer

If the name is truely dynamic, then I don't think JAXB will help you these. If you have a defined number of various element names then you could use inheritance like the other post suggested. If the number of elements and names is unknown I would recommend using something like this:

@XmlMixed
@XmlAnyElement
public List<Object> getObjects() {
    return objects;
}

This would bring the element is a just a DOM element. You could then use JAXB a second time to go from each of the elements into your custom type.

That would be if you had to use JAXB. You might find it easier to just use the SAX or DOM APIs directly for data like this. JAXB is really intended for well defined data that can be represented as a schema.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...