3

I'm trying to figure out the best way to unmarshal some data from a public API (meaning I have no control over how it is serialized into XML).

<Show>
 <name>Buffy the Vampire Slayer</name>
 <totalseasons>7</totalseasons>
 <Episodelist>
  <Season no="1">
   <episode>...</episode>
   <episode>...</episode>
   <episode>...</episode>
   <episode>...</episode>
  </Season>
  <Season no="2">...</Season>
  <Season no="3">...</Season>
 </Episodelist>
</Show>

Above is a sample of the XML returned from a ReSTful query. Ideally, I'd like to figure out how to do two things; 1) merge all the season lists into one list of episodes and 2) is it possible to access only child elements and ignore parent elements when unmarshalling XML (ex. Access EpisodeList only, ignoring Show)?

Thank you for any help! This is my first SO post (still fairly new to programming).

RNGuy
  • 625
  • 6
  • 7
  • If the public api provides and xsd you could convert /unmarshal the xml to java object using jaxb. Then just do what you will with the java object. – rsavchenko Apr 28 '15 at 22:28
  • Why you don't use a xml parser ? – Franky Apr 29 '15 at 13:42
  • @rsavchenko As far as I know, they don't provide an XSD (I'm also unsure as to how that would help me)... – RNGuy Apr 29 '15 at 14:48
  • @Franky I suppose I could look into that. I was hoping to accomplish this using JAX-B (by using an XmlAdapter class, I'm thinking). – RNGuy Apr 29 '15 at 14:48
  • have a look to those links http://stackoverflow.com/questions/8186896/how-do-i-parse-this-xml-in-java-with-jaxb and http://stackoverflow.com/questions/27643822/marshal-un-marshal-list-objects-in-jersey-jax-rs-using-jaxb?rq=1 – Franky Apr 29 '15 at 21:19

1 Answers1

0

I ended up creating some "helper" classes to extract the data I needed. I wrote a getEpisodeList method in EpisodeListHelper which rolls all the episodes up into a single list.

EpisodeListHelper class

@XmlRootElement(name="Show")
@XmlAccessorType(XmlAccessType.FIELD)
public class EpisodeListHelper {
    @XmlElementWrapper(name="Episodelist")
    @XmlElement(name="Season")
    private List<SeasonHelper> seasonList;
...
}

SeasonHelper class

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class SeasonHelper {
    @XmlElement(name="episode")
    private List<Episode> list;
...
}
RNGuy
  • 625
  • 6
  • 7