[Java] -How to use JAX-B to parse XMLfiles ?

What is it?

JAX-B is the Java specification that allows us to directly associate a class to an XML file, so we need to create a class that represents our xml, add @XmlRootElement annotation and finally use the JAXBContext class to parse the document.

When I should use it ?

The main disadvantage of JAX-B is that the files are also interpreted using trees, when the file is too big we end up spending a lot of memory, however, we have the same DOM problems. JAX-B is interesting to when we have small files and we will use all the information this file.

How to use it?

First, you need create a JAVA class to interpreter all data. You will use Annotations to define how the file need be parse. Below is an example.

Example:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Sell {

    @XmlElement(name="payment") 
    private String payment;
    @XmlElementWrapper(name="products")
    @XmlElement(name="product")
    private List<Product> products;

    public void setPayment(String payment) {
        this.payment = payment;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public String getPayment() {
        return payment;
    }

    public List<Product> getProducts() {
        return products;
    }

    // To print pretty :-)
    @Override
    public String toString() {
        return "Payment: "+ payment + "products: \n " + products;
    }
} 

Now you can parse the file:

JAXBContext content = JAXBContext.newInstance(Sell.class);
Unmarshaller unmarshaller = content.createUnmarshaller();
Sell sell = (Sell) unmarshaller.unmarshal(new File("src/sell.xml"));

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s