Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I have an XML file which is used to config some rules, it does not has complex structure, but this configuration is used anywhere in my system, so I want to parse this XML to java object and design as singleton mode, is any good way I can use it to unmarshal XML to Java object directly without write much codes?

I did some research on Google and known JAXB is choice, I used xjc to generate java object source class according xsd file, after unmarshal I will directly get these configurationType object, is it necessary I convert again, I see most coders did this, but why? Because they are some data, just from the object generated to JAXB and copy to yourself created POJO object

1 Answer

0 votes
by (13.1k points)

JAXB is an ideal solution. But you don’t necessarily need xsd and xjc for that. More often than you don’t have an xsd but you know what your xml is. Simple analyze xml, e.g.,

<customer id="100">

    <age>29</age>

    <name>mkyong</name>

</customer>

Create necessary model class:

@XmlRootElement

public class Customer {

    String name;

    int age;

    int id;

    public String getName() {

        return name;

    }

    @XmlElement

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    @XmlElement

    public void setAge(int age) {

        this.age = age;

    }

    public int getId() {

        return id;

    }

    @XmlAttribute

    public void setId(int id) {

        this.id = id;

    }

}

Try to unmarshal:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));

Want to learn Java? Check out the core Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 4, 2019 in Java by Anvi (10.2k points)
+10 votes
2 answers
asked May 30, 2019 in Java by tommas (1k points)
0 votes
1 answer
asked Jul 18, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)

Browse Categories

...