Continuing on from the previous article, we will now make some adjustments to the XML and demonstrate the changes required to deserialise it into a Java obect.
<?xml version="1.0" encoding="UTF-8"?> <xml> <ips state="normal"> <ip>192.168.*.1</ip> <ip>127.0.0.1</ip> <ip>10.0.*</ip> </ips> <ips state="active"> <ip>126.111.*</ip> <ip>127.0.0.1</ip> <ip>99.99.1.1</ip> </ips> </xml>
Here we have changed the structure by saying that the ips tag is actually a list item and contains an attribute. How does our Java object change to represent this structual change?
private class XML {
private List<IPData> ips;
public XML(List<IPData> ips) {
}
}
private class IPData {
String state;
List<String> list = new ArrayList<String>();
}
// The following describes this to XStream
xstream.alias("xml", XML.class);
xstream.addImplicitCollection(XML.class, "ips", IPData.class);
xstream.alias("ips", IPData.class);
xstream.aliasAttribute(IPData.class, "state", "state");
xstream.addImplicitCollection(IPData.class, "list", "ip", String.class);
In this case, we have changed the constructor definition to a list of IPData instances. This is enough to get XStream to deserialise the ips tag correctly. Also we have added the attribute definiation to convert the attribute of ips to a field of the IPData class.
The complete code listing for this is below:
package xstream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.util.ArrayList;
import java.util.List;
public class Two {
public static void main(String[] args) {
XStream xstream = new XStream(new DomDriver());
xstream.alias("xml", XML.class);
xstream.addImplicitCollection(XML.class, "ips", IPData.class);
xstream.alias("ips", IPData.class);
xstream.aliasAttribute(IPData.class, "state", "state");
xstream.addImplicitCollection(IPData.class, "list", "ip", String.class);
XML data = (XML) xstream.fromXML(
Two.class.getResourceAsStream("ip-ranges-two.xml"));
for (IPData d : data.ips) {
System.out.println("State: " + d.state);
for (String s : d.list) {
System.out.println(s);
}
}
}
private class XML {
private List<IPData> ips;
public XML(List<IPData> ips) {
}
}
private class IPData {
String state;
List<String> list = new ArrayList<String>();
}
}
No comments:
Post a Comment