user1189571
user1189571

Reputation: 305

JAXB unmarshalling XML element with different tags

I have xml file with this kind of structure:

<root>
    <elements>
        <element>
            <id>1</id>
            <tag1>some string</tag1>
        </element>
        <element>
            <id>1</id>
            <tag2>some other string</tag2>
        </element>
    </elements>
</root>

Is it possible to unmarshall that kind of XML to an object. Problem is that each element has some tags that are unique. I was thinking to put those values in List, but i have no idea how to do that.

Upvotes: 0

Views: 1007

Answers (1)

comanitza
comanitza

Reputation: 1103

Yes, it is possible and quite easy, make an Element object for the element tag and put there all possible sub tags, if JAX-B can't find them in you XML it will leave them as null, so you will get a decent object.

A simple JAX-B intro can be found here: http://www.mkyong.com/java/jaxb-hello-world-example/

If the possible sub tags of the element tag are just too many, change rapidly or are unknown you could try to go with a <String, String> structure, something like the one described here: How to serialize HashTable<String, String> to XML using JAXB?

But for most cases I would chose the first option.

Upvotes: 2

Related Questions