【发布时间】:2018-01-21 22:26:04
【问题描述】:
我一直在努力使下面的程序工作,但我的代码或@XmlPath 注释似乎存在一些严重的缺陷。 我正在尝试解析的 XML:
<?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>
我正在创建的 Pojo:
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;
}
我如何解组 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);
}
}
上面的输出是:
Information(customerId=null, billingAddressId=address1)
显然输出不正确。 customerId 显示 null 而不是 customer1。但是,如果我在 pojo 类中注释掉第 (2) 行,那么 customerId 将获得正确的值。为什么会这样?为什么我不能在上面的程序中读取正确的customerId 值?
【问题讨论】: