java - SimpleXML: element with elements list or text -


i must parse xml file can 2 types:

<property>     <value>some text</value> </property> 

and

<property>     <value>         <item id="first_id"/>         <item id="second_id"/>         <item id="third_id"/>     </value> </property> 

how can java?

i created class:

@root(strict = false) public class propertyvalue {     @elementlist(inline = true, required = false)     private list<itemdata> items;      @text(required = false)     private string text; } 

itemdata item class.

but not work. code gives me exception:

org.simpleframework.xml.core.textexception: text annotation @org.simpleframework.xml.text(data=false, empty=, required=false) on field 'text' private java.lang.string propertyvalue.text used elements in class propertyvalue 

i solved problem!

i used following question answer: deserializing xml tag text , subtags using retrofit

i created class convert xml files want (sorry code :-( ):

public class propertyvalueconverter implements converter<propertyvalue> {     @override     public propertyvalue read(inputnode node) throws exception {         propertyvalue propertyvalue = new propertyvalue();         list<itemdata> propertyvalueitems = new arraylist<>();         string propertyvaluetext = "";          inputnode itemnode = node.getnext("item");         while (itemnode != null) {             string itemid = itemnode.getattribute("id").getvalue();             itemdata itemdata = new itemdata();             itemdata.setid(itemid);             propertyvalueitems.add(itemdata);             itemnode = node.getnext("id");         }          if (propertyvalueitems.size() == 0) {             propertyvaluetext = node.getvalue();         }          propertyvalue.setitems(propertyvalueitems);         propertyvalue.settext(propertyvaluetext);          return propertyvalue;     }      @override     public void write(outputnode node, propertyvalue value) throws exception {      } } 

then changed propertyvalue class:

@root(strict = false) @convert(value = propertyvalueconverter.class) public class propertyvalue {     private list<itemdata> items;      private string text;      public list<itemdata> getitems() {         return items;     }      public void setitems(list<itemdata> items) {         this.items = items;     }      public string gettext() {         return text;     }      public void settext(string text) {         this.text = text;     } } 

then set simplexml converter factory:

private static strategy strategy = new annotationstrategy(); private static serializer serializer = new persister(strategy);  private static retrofit.builder builder =         new retrofit.builder()                 .baseurl(api_base_url)                 .addconverterfactory(simplexmlconverterfactory.create(serializer)); 

so, works me.


Comments