Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (partly) deserialize xml with errors using XStream

Tags:

java

xml

xstream

Suppose I have an xml file that should look like this:

<list>
 <item>
  <id>123</id>
  <name>someName</name>
 </item>
 <item>
  <id>234</id>
  <name>anotherName</name>
 </item>
 <item>
  <id>345</id>
  <name>aThirdName</name>
 </item>
</list>

I parse it using XStream and the following classes:

class ListXML {
 public List<ItemXML> list;
}

class ItemXML {
 public String id;
 public String name;
}

and the following code:

XStream xstream = new XStream(new DomDriver());
xstream.alias("list", ListXML.class);
xstream.alias("item", ItemXML.class);
xstream.addImplicitCollection(ListXML.class, "item");
ListXML result = (ListXML) xstream.fromXML(in);

So far so good. However, I now came across a case where I had the following xml as input:

<list>
 <item>
  <id>123</id>
  <name>someName</name>
 </item>
 <item>
  <id>234</id>
  <aTagUnknownToMe>blabla</aTagUnknownToMe>
 </item>
 <item>
  <id>345</id>
  <name>aThirdName</name>
 </item>
</list>

Is there a way to change my code to be "more robust", so I can get hold of the items with id 123 and 345 without knowing the "aTagUnknownToMe" tag?

like image 918
user3105436 Avatar asked Nov 10 '22 16:11

user3105436


1 Answers

Yes, you can.

XStream xstream = new XStream();
xstream.ignoreUnknownElements();

or

XStream xstream = new XStream();
xstream.ignoreUnknownElements("somePattern");

Those methods are available since XStream 1.4.5.

like image 119
pablosaraiva Avatar answered Nov 14 '22 21:11

pablosaraiva