michdraft michdraft - 2 months ago 16
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

Configuration.java
?

XML

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


Configuration.java


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

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

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

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

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

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

}

kjp kjp
Answer

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

Comments