Hello, I need to parse this xml :
<?xml version="1.0" encoding="UTF-8"?> <Orders> <AddOrder book="book-1" operation="SELL" price="100.50" volume="81" orderId="1" /> <AddOrder book="book-3" operation="BUY" price=" 99.50" volume="86" orderId="2" /> <DeleteOrder book="book-2" orderId="104" /> <AddOrder book="book-1" operation="BUY" price=" 99.70" volume="16" orderId="3" /> <AddOrder book="book-3" operation="SELL" price="100.00" volume="80" orderId="4" /> <DeleteOrder book="book-2" orderId="104" /> <AddOrder book="book-3" operation="SELL" price="100.80" volume="24" orderId="149" /> </Orders>
I'm trying to do this with JAXB . This is my first acquaintance with him on this, do not throw tomatoes please. I'm trying to do it like this:
Application class:
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "AddOrder") @XmlType(propOrder = {"book","operation","volume","price","orderId"}) public class Order { private String book; private String operation; private int volume; private float price; private int orderId; public String getBook() { return book; } @XmlElement public void setBook(String book) { this.book = book; } public String getOperation() { return operation; } @XmlElement public void setOperation(String operation) { this.operation = operation; } public int getVolume() { return volume; } @XmlElement public void setVolume(int volume) { this.volume = volume; } public float getPrice() { return price; } @XmlElement public void setPrice(float price) { this.price = price; } public int getOrderId() { return orderId; } @XmlElement public void setOrderId(int orderId) { this.orderId = orderId; } }
The parser itself:
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; public class JaxbParser implements Parser { @Override public Object getObject(File file, Class c) throws JAXBException { JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); return unmarshaller.unmarshal(file); } }
Well, when I try to try this thing:
public static void main(String[] args) throws JAXBException { Parser parser = new JaxbParser(); File file = new File("/Users/pavel/Desktop/order1.xml"); Order order = (Order) parser.getObject(file, Order.class); System.out.println(order); }
Everything falls with an error:
unexpected element (uri: "", local: "Orders"). Expected elements are <{} AddOrder>
And I would think that the whole thing is in the tag at the beginning of the file, but when I left one line in the file <AddOrder book="book-1" operation="SELL" price="100.50" volume="81" orderId="1" /> (everything else was deleted) as an experiment, then an object was created of course, but with empty fields, that is, data, so it was not recorded in the object.
Please help me figure out what I'm doing wrong. How do I parse this file?