javaxmljaxbpojo

Map XML list / XML elements with different attribute values to separate fields


I have an XML file that looks like this:

XML file:

<foobar name="quux">
    <supplement key="head">this is a text row</supplement>
    <supplement key="body">this is some other text row</supplement>
</foobar>

I would like to have <supplement> mapped to two separate variables; head and body.

Java POJO:

@XmlRootElement(name = "foobar")
@XmlAccessorType(XmlAccessType.FIELD)
public class Foobar {
    @XmlAttribute
    private String name;

    private String head;  // should be mapped to XMLs supplement:key=head

    private String body;  // should be mapped to XMLs supplement:key=body
}

Can this be done? If so how?

Another doable solution would be to have both <supplement>-tags added to a HashMap<String, String>, where the key-value is used as index, but I have failed to do this unfortunately.

As a workaround I have a solution to map <supplement> as a list, using:

@XmlElement(name = "supplement")
private List<NewSupplement> supplements = new ArrayList<>();

The problem with this solution is that list index value is decided by the order of <supplement>-tags in the XML file, ie. if key="head" comes first in the XML file this is added to index 0 but if key="body" comes first that is added to index 0, which might cause me some problems / unnecessary headache.

I would rather have the first solution (or a HashMap) if that is doable. Any suggestions?


Solution

  • I managed to solve this issue myself after some more hours, with the help of @XmlPath from EclipseLink MOXy. I mapped the <supplement>-tags to two individual variables.

    @XmlRootElement(name = "foobar")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Foobar {
        @XmlAttribute
        private String name;
    
        @XmlPath("supplement[@key='head']/text()")
        private String head;  // maps to XMLs supplement:key=head
    
        @XmlPath("supplement[@key='body']/text()")
        private String body;  // maps to XMLs supplement:key=body
    }
    

    EclipseLink MOXy, maven dependency

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.moxy</artifactId>
        <version>2.4.0</version>
    </dependency>