michdraft michdraft - 4 months ago 28
Java Question

xml representation in java class?

I'm trying to convert this XML to Java object and then updating key and value and then save it to XML.I can convert simple XML but this one has two attribute which is the same.
Can anybody help me to represent this xml in java class as



<?xml version="1.0" encoding="utf-8" ?>
<add key="mode" value="1"/>
<add key="type" value="shs"/>


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Configuration {
String appSettings;
String add;
String key;
String value;

public String getAppSettings() { return appSettings; }
public void setAppSettings(String appSettings) { this.appSettings = appSettings;}

public String getAdd() { return add; }
public void setAdd(String add) { this.add = add; }

public String getKey() { return key; }
public void setKey(String key) { this.key = key; }

public String getValue() { return value; }
public void setValue(String value) { this.value = value; }


kjp kjp

Use JAXB if you want fine control over the XML to POJO creation. But you will have to specify the structure of your XML in an XSD first and let JAXB generate the Java classes for you.

Another way is to use XStream.

XStream xstream = new XStream();
Configuration config= (Configuration)xstream.fromXML(xml);

But you might have to update your Configuration class to use List for the add nodes as Kuldeep Jain said in his answer.

Edit: Take a look at the 2-minute XStream tutorial also - http://x-stream.github.io/tutorial.html