Java: XML to Object (or Array)

前端 未结 5 1530
清酒与你
清酒与你 2021-01-15 08:04

How could I convert a XML Document to a Java Object (or Array)? I readed the XML like this:

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInsta         


        
相关标签:
5条回答
  • 2021-01-15 08:29

    I would look at JAX/B, which gives a way to "bind" between Java objects and XML representations.

    I've got a tiny write-up of doing it with Rational Eclipse-based tooling here, but there appear to be (never used them myself) straight Eclipse plugins too, for example this.

    Indeed writing JAX/B by hand is possible, gets a bit dull for complex XML, but annotations are quite easy.

    0 讨论(0)
  • 2021-01-15 08:39

    You will need JAXB unmarshaling.

    0 讨论(0)
  • 2021-01-15 08:45

    Use XStream.

    Object to XML

    Person joe = new Person("Joe", "Walnes");
    joe.setPhone(new PhoneNumber(123, "1234-456"));
    joe.setFax(new PhoneNumber(123, "9999-999"));
    String xml = xstream.toXML(joe);
    

    The resulting XML looks like this:

    <person>
      <firstname>Joe</firstname>
      <lastname>Walnes</lastname>
      <phone>
        <code>123</code>
        <number>1234-456</number>
      </phone>
      <fax>
        <code>123</code>
        <number>9999-999</number>
      </fax>
    </person>    
    

    XML to Object

    Person newJoe = (Person)xstream.fromXML(xml);
    

    Also see

    • Reference

    • Simple

    0 讨论(0)
  • 2021-01-15 08:45

    I recommend using XStream for XML (de)serialization. It's way simpler than using Java's built-in XML APIs.

    0 讨论(0)
  • 2021-01-15 08:54

    I have used Simple XML and have found it quite easy and powerful. I am not as familiar with XStream, but Simple lets you control your XML schema using annotations which gives you a lot of freedom. The guy who writes it is always responsive on his mailing list.

    0 讨论(0)
提交回复
热议问题