1

Given something like:

<root>
    <wrapper>
        <wrapped id="..."/>
        <wrapped id="..."/>
    </wrapper>
</root>

how can I map it to this POJO:

public class Root {
    public Set<UUID> myIds = new LinkedHashSet();
}

I am wondering since @XmlElement( name = "wrapped" ) @XmlElementWrapper( name = "wrapper" ) works somewhat similar to what I want, is there something to get the attribute?

note: i am not using moxy so as far as I know, I cannot use xpaths. I am trying to avoid the @XmlJavaTypeAdapter route.

Aarjav
  • 1,334
  • 11
  • 22

1 Answers1

0

You need to modify your root class a little bit, so that it will contain a Set<Wrapped> instead of a Set<UUID>.

@XmlRootElement(name = "root")
public class Root {

    @XmlElementWrapper(name = "wrapper")
    @XmlElement(name = "wrapped")
    public Set<Wrapped> myWrappeds = new LinkedHashSet<>();
}

And you need a separate class for the <wrapped> elements.
Surprisingly for me, you don't need an @XmlJavaAdapter for id here, because JAXB already has a built-in converter between java.util.UUID and String.

public class Wrapped {

    @XmlAttribute(name = "id")
    public UUID id;
}

I have checked the above with this XML input file

<root>
    <wrapper>
        <wrapped id="550e8400-e29b-11d4-a716-446655440000"/>
        <wrapped id="550e8400-e29b-11d4-a716-446655440001"/>
    </wrapper>
</root>

and this main method which reproduces the original XML:

public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    File file = new File("root.xml");
    Root root = (Root) unmarshaller.unmarshal(file);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(root, System.out);
}
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • Hey thanks for your time and looking into this. Getting `Set` instead of `Set` is what I am looking for so there is no need to code for converting between `UUID` and `Wrapped` objects. For now I am using what basically what you have + `@XmlJavaAdapter` to do the conversion between `UUID` and `Wrapped` objects so the pojo still has `Set` – Aarjav Jul 06 '17 at 16:57