1

I have seen the following syntax in various stack overflow postings and in blog entries:

JAXBElement<SomeClass> sc = unmarshaller.unmarshal(is, SomeClass.class);

So why does eclipse give me a compilation error when I try to use this syntax? And why is this syntax not in the api, which you can read at this link?

Here is the compilation error:

The method unmarshal(Node, Class<T>) in the type Unmarshaller  
is not applicable for the arguments (FileInputStream, Class<SomeClass>)  

Here is a complete method that would use the above syntax:

public void unmarshal() throws FileNotFoundException{
    Unmarshaller unmarshaller;
    try {
        JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
        unmarshaller = ctx.createUnmarshaller();
        FileInputStream is = new FileInputStream("path/to/some.xml");
        JAXBElement<SomeClass> sc = unmarshaller.unmarshal(is, SomeClass.class);//error here
        System.out.println("title is: "+sc.getValue().getTitle());
    } catch (JAXBException e) {e.printStackTrace();}
}

This syntax is given in examples where a developer needs to unmarshal xml that does not contain a defined root element. One example is Sayantam's answer to this question.

Community
  • 1
  • 1
CodeMed
  • 9,527
  • 70
  • 212
  • 364

1 Answers1

2

The error is due to wrong type argument, FileInputStream instead of Node.

This method is more appropriate to unmarshal a piece of the xml. When you want to parse the entire file, use the unsmarshal(File) method.

public void unmarshal() throws FileNotFoundException{
    Unmarshaller unmarshaller;
    try {
        JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
        unmarshaller = ctx.createUnmarshaller();
        FileInputStream is = new FileInputStream("path/to/some.xml");
        SomeClass sc = (SomeClass) unmarshaller.unmarshal(is);
        System.out.println("title is: "+sc.getValue().getTitle());
    } catch (JAXBException e) {e.printStackTrace();}
}

If you don't want to make a cast, try this:

public void unmarshal() throws FileNotFoundException{
    Unmarshaller unmarshaller;
    try {
        JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
        unmarshaller = ctx.createUnmarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        StreamSource streamSource = new StreamSource("path/to/some.xml");
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(streamSource);
        JAXBElement<SomeClass> sc = unmarshaller.unmarshal(xmlStreamReader, SomeClass.class);//error here
        System.out.println("title is: "+sc.getValue().getTitle());
    } catch (JAXBException e) {e.printStackTrace();}
}
DiogoSantana
  • 2,404
  • 2
  • 19
  • 24
  • I had to change your `XMLInputFactory.newFactory()` to `XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance()`, but otherwise your second example does the trick. Thank you. +1 – CodeMed Oct 22 '14 at 00:49