Skip to content

Instantly share code, notes, and snippets.

@gipi
Created November 22, 2011 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gipi/1386262 to your computer and use it in GitHub Desktop.
Save gipi/1386262 to your computer and use it in GitHub Desktop.
Deserialize XML into Java objects
XStream xstream = new XStream();
// http://stackoverflow.com/questions/3136234/xstream-root-as-a-collection-of-objects/3138114#3138114
xstream.alias("products", List.class);
xstream.alias("product", Product.class);
xstream.useAttributeFor(Product.class, "id");
List<Product> ps = (List<Product>)xstream.fromXML("<products><product id=\"1\"><name>Gatti</name><descriptionShort>Pelosi e caldi</descriptionShort></product><product id=\"2\"><name>Cani</name><descriptionShort>Abbaiano</descriptionShort></product></products>");
Iterator<Product> i = ps.iterator();
while (i.hasNext()) {
Object o = i.next();
if (!(o instanceof Product)) {// just in case some XML error
android.util.Log.i(TAG, "class: " + o.getClass().getCanonicalName());
continue;
}
Product p = (Product)o;
android.util.Log.i(TAG, "ID: " + p.id + " name: " + p.name + " descriptionShort: "+ p.descriptionShort);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment