-1

I was just wondering if someone can show me a quick way of converting an XML file to Java object from this sample:

- <VM-DataCalculator>
- <device name="Blackberry" fname="BlackBerry">
- <dataCategory>
  <name>email</name> 
  <datarate>0.002</datarate> 
  <max>300</max> 
  <percent>12</percent> 
  <timeunit>month</timeunit> 
  </dataCategory>
- <dataCategory>
  <name>emailAttachment</name> 
  <datarate>0.2</datarate> 
  <max>100</max> 
  <percent>10</percent> 
  <timeunit>month</timeunit> 
  </dataCategory>

Full file is available here: http://www.virginmobile.ca/en/catalogue/VMDataCalculator.xml

Any help would be appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Demitri
  • 19
  • 1
  • 3

2 Answers2

2

The standard solution, using nothing but the Java framework would be to use JAXP. There are numerous other ways.

JAXP is a bit bloated, to parse some XML into DOM you'd have to do the following:

DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
dbfactory.setNamespaceAware(true);
DocumentBuilder domparser = dbfactory.newDocumentBuilder();
Document doc = domparser.parse("http://www.virginmobile.ca/en/catalogue/VMDataCalculator.xml");
Community
  • 1
  • 1
Matthijs Bierman
  • 1,720
  • 9
  • 14
2

You need JAXB. This is basically how it works, you create your model classes

@XmlRootElement(name="VM-DataCalculator")
class VMDataCalculator {
    @XmlElement(name = "device")
    List<Device> devices;
}

@XmlRootElement
class Device {
    @XmlElement(name = "dataCategory")
    List<DataCategory> dataCategories;
}

@XmlRootElement
class DataCategory {
    @XmlElement
    String name;
          ....
}

and unmarshal your xml

 VMDataCalculator c = JAXB.unmarshal(new File("1.xml"), VMDataCalculator.class);

more details here http://docs.oracle.com/javase/tutorial/jaxb/intro/index.html

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275