Chun ping Wang
Chun ping Wang

Reputation: 3929

how to parse xml into java object?

Hi i have an xml in the following format generated from a web service.

<root>
   <item>
       <name>test</name>
       <description>test description</description>
       <link>http://xxx</link>
   </item>
</root>

I read the file

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

now that I have doc, how would i get the and for each

and put it into a object call Item

public class Item {
      private final String name;
      private final String desc;
      private final String link;


      public Item(final String name, final String desc, final String link) {
           super();
           this.name = name;
           this.desc = desc;
           this.link = link;
      }

      // ... getters for name and desc
  }

I look at examples of dom element but they seem confusing. Whats the most easiest/efficent way to parse XML into java object. Can i get an example?

Using xstream works.

I did

final XStream xstream = new XStream(new DomDriver());
xstream.alias("root", LineItem.class);
xstream.aliasField("name", Item.class, "name");
xstream.aliasField("description", Item.class, "desc");
xstream.aliasField("link", Item.class, "link");
xstream.fromXml(xml);

Upvotes: 1

Views: 3524

Answers (1)

Ahamed
Ahamed

Reputation: 39695

XStream can parse xml to java objects. XML need not to be created by XStream.

Example Code is here

Hope this would help you.

Upvotes: 1

Related Questions