Question

I have an xml document like this:

<root>
    <device>
        <v1>blah</v1>
    </device>
</root>

I want to parse this document, but just the

    <device>
        <v1>blah</v1>
    </device>

part. I want to ignore the root element. How can I unmarshal this with jaxb?

Was it helpful?

Solution

Assuming that your JAXB definition knows nothing about <root>, i.e. you can't just unmarshal the whole thing and look inside the resulting Root object:

  1. Parse into a Document.
  2. Use XPath / DOM traversal / whatever to get [a] reference[s] to the device Node[s].
  3. Use unmarshaller.unmarshal (node).

OTHER TIPS

You can do the following:

  • Parse the XML with a StAX XMLStreamReader.
  • Advance the XMLStreamReader to the element you wish to unmarshal.
  • Use one of the unmarshal methods that take an XMLStreamReader.

Example

import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

public class UnmarshalDemo {

    public static void main(String[] args) throws Exception {
        // Parse the XML with a StAX XMLStreamReader
        XMLInputFactory xif = XMLInputFactory.newFactory();
        StreamSource xml = new StreamSource("input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);

        // Advance the XMLStreamReader to the element you wish to unmarshal
        xsr.nextTag();
        while(!xsr.getLocalName().equals("device")) {
            xsr.nextTag();
        }

        // Use one of the unmarshal methods that take an XMLStreamReader
        JAXBContext jc = JAXBContext.newInstance(Device.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Device device = (Device) unmarshaller.unmarshal(xsr);
        xsr.close();
    }

}

For More Information

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top