Search code examples
javaxmlxpathmoxy

MOXy @XmlPath annotation can't read same XPaths more than once


I have been working hard to make below program work, but there seems to be some serious flaw either in my code or with @XmlPath annotation. XML that I am trying to parse:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<information>
    <customer id="customer1">
        <billingAddress id="address1">
            <street id="street1">1 Billing Street</street>
            <street id="street2">2 Billing Street</street>
        </billingAddress>
    </customer>
</information>

The Pojo that I am creating:

package parser;


import lombok.ToString;
import org.eclipse.persistence.oxm.annotations.XmlPath;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@ToString
@XmlRootElement(name = "information")
@XmlAccessorType(XmlAccessType.FIELD)
public class Information {

    @XmlPath("customer/@id")//-------------------------------------> (1)
    private String customerId;

    @XmlPath("customer[@id='customer1']/billingAddress/@id") //-----> (2)
    private String billingAddressId;                          

}

How I am unmarshalling the xml:

import parser.Information;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;

public class Main {
    public static void main(String[] args) throws JAXBException {
        JAXBContext jaxbContext =  org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(new Class[]{Information.class}, null);
        Unmarshaller jaxbMarshaller = jaxbContext.createUnmarshaller();

        Information information = (Information)jaxbMarshaller.unmarshal(new File("information.xml"));
        System.out.println(information);
    }
}

Output for the above is:

Information(customerId=null, billingAddressId=address1)

Clearly the output is incorrect. customerId is showing null instead of customer1. However, if I comment out the line (2) in pojo class then the customerId is getting correct value. Why is it so ? Why can't I read the correct customerId value in above program ?


Solution

  • Removing the [@id='customer1'] from the 2nd XmlPath does solve the issue for the provided code, even though I assume the real Information entity has much more fields which you address with XmlPath.

    Why don't you use some classes to reflect the XML structure ... kinda like object-oriented? It'll simplify the JAXB modelling.