这是我的Parser类
public class Test { public static void main(String args[]) throws Exception { File file = new File("D:\\Test.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(MyOrder.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); MyOrder customer = (MyOrder) jaxbUnmarshaller.unmarshal(file); System.out.println(customer.getorder().getSide()); } }
这是MyOrder.java文件
@XmlRootElement(name = "BXML") public class MyOrder { @XmlElement(name = "Bag") protected Order order; public MyOrder() { } @XmlAttribute public Order getorder() { return order; } public void setorder(Order order) { this.order = order; } }
这是我的域对象(Order.java)
@XmlRootElement(name = "BXML") public class Order { public Order() { } @XmlAttribute(name = "Side") protected BigInteger Side; @XmlValue public BigInteger getSide() { return Side; } public void setSide(BigInteger side) { Side = side; } }
这是我试图运行程序时遇到的异常
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions @XmlAttribute/@XmlValue need to reference a Java type that maps to text in XML. this problem is related to the following location: at public com.Order com.MyOrder.getorder() at com.MyOrder Class has two properties of the same name "order" this problem is related to the following location: at public com.Order com.MyOrder.getorder() at com.MyOrder this problem is related to the following location: at protected com.Order com.MyOrder.order at com.MyOrder
对于@ XmlAttribute / @ XmlValue,需要引用映射到XML中的文本的java类型.问题您需要将JAXBContext的初始化更改为以下内容:
JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] {MyOrder.class,Order.class});
对于Class有两个同名“order”问题的属性,需要更改受保护Order顺序的定义;私人订单;
此外,您希望将Order类的@XmlRootElement(name =“BXML”)更改为@XmlRootElement(name =“Order”).