简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM