简体   繁体   中英

How to parse this xml to java object (Retrofit2+SimpleXML)? (PersistenceException error)

my Retrofit call failed with error :

org.simpleframework.xml.core.PersistenceException: Element 'item' is already used with @org.simpleframework.xml.ElementList(data=false, empty=true, entry=, inline=false, name=item, required=false, type=void) on field 'medias' private java.util.ArrayList packageName.FeedTag.medias at line 58

which I guessed is caused by incorrectly mapping the XML to POJO class.

So, can anyone tell me what's wrong with my code? I've tried looking at SimpleXML examples and tutorial but I can't find info with the use case such as mine. (This is my first time working with Retrofit and/or SimpleXML.)

This is my XML

<xml>
<feed>
<item>
  <id>0</id>
  <title>Lorem ipsum</title>
</item>

<item>
  <id>1</id>
  <title>Lorem ipsum dolor</title>
  <comments>
     <item>
        <id>3</id>
     </item>
  </comments>
  <medias>
     <item>
       <id>4</id>
       <title>Media 1</title>
     </item>

      <item>
        <id>8</id>
        <title>Media 2</title>
      </item>
    </medias>
  </item>

</feed>
</xml>

My objects is like this :

XmlTag.java

@Root(name = "item", strict = false)
public class XmlTag{

   @Path("feed")
   @ElementList(name = "item", required = false)
   private List<FeedTag> feeds;

   //empty constructor, setter, getter...    

}

FeedTag.java

@Root(name = "item", strict = false)
public class FeedTag{

   @Element(name = "title", required = false)
   private String title;

   @Path("comments")
   @ElementList(name = "item", required = false)
   private List<CommentTag> comments;

   @Path("medias")
   @ElementList(name = "item", required = false)
   private List<MediaTag> medias;

   //empty constructor, setter, getter...    

}

and CommentTag and MediaTag are similar to FeedTag.

I've finally found what's wrong with my code after some T&Es.

It was because of the @ElementList(name = "item", required = false) line doesn't have inline=true in it. From my trial and error, with that parameter, simplexml only parse direct <item/> child of the given @Path', so other tags with same tag name is safe as their ` tag hasn't been used yet by other tags.

So, as long as I make sure that any @ElementList of tags that have possible duplicate tag name has inline=true , the PersistenceException I got before won't return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM