2014-10-22 104 views
1

我見過的語法如下各種堆棧溢出的帖子和博客條目:兩個的Unmarshaller.unmarshal()的元素形式

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

那麼,爲什麼日食給我一個編譯錯誤,當我嘗試使用此句法?爲什麼這個語法不在api中,你可以閱讀at this link

以下是編譯錯誤:

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

這裏是一個將使用上述語法的完整方法:

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();} 
} 

此語法在開發者需要組XML實例因爲不包含已定義的根元素。一個例子是Sayantam的回答to this question

+0

什麼是編譯錯誤? – Denise 2014-10-22 00:16:40

+0

請同時發佈你看到這個例子的地方(鏈接)。 – 2014-10-22 00:32:44

回答

2

錯誤是由於錯誤的類型參數FileInputStream而不是節點。

此方法更適合解組一個xml。當你想分析整個文件時,使用unsmarshal(File)方法。

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();} 
} 

如果你不想做一個演員,試試這個:

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();} 
} 
+0

我不得不將'XMLInputFactory.newFactory()'改成'XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance()',但是否則你的第二個例子就會訣竅。謝謝。 +1 – CodeMed 2014-10-22 00:49:35