Below is the xml I have to work with:
<watermarks identifier="X" hostname="X">
<watermark type="XX" value="1234"/>
<watermark type="YY" value="1234" />
</watermarks>
I just want to get a list of Watermark objects using JAXB without creating a new Watermarks class. Is it possible or should I have to create a Watermarks class which contains a list of Watermark objects ?
Thanks.
You could use a StAX (JSR-173) XMLStreamReader
to parse the XML document (an implementation is included in the JDK/JRE since Java SE 6). Then you could advance it to advance to each watermark
element and then have JAXB (JSR-222) unmarshal that.
Demo
Assuming the Watermark
class is annotated with @XmlRootElement
you could do the following.
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Watermark.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource source = new StreamSource("input.xml");
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(source);
xsr.nextTag(); // Advance to "watermarks" element
xsr.nextTag(); // Advance to "watermark" element
while(xsr.getLocalName().equals("watermark")) {
Watermark object = (Watermark) unmarshaller.unmarshal(xsr);
System.out.println(object);
xsr.nextTag();
}
}
}
Full Example
Generic List Wrapper Class
In my answer to the question below I provided an example of a generic list wrapper class that you may find useful.