2012-12-04 41 views
2

我有一本書Book defined,我想創建一個JAXBElement對象,該對象將包含與來自String對象的XML對應的信息。從字符串創建JAXBElement <Book>

例如,我可以有這樣的:

String code = "<book><title>Harry Potter</title></book>"; 

現在,我想創建一個的JAXBElement,從該字符串開始。我需要字符串來做一些我無法使用JAXBElement的驗證。

那麼,我可以做我想要的嗎?如果是,如何?

謝謝!

索林

回答

4

如果您使用的unmarshal方法,需要一個Class參數,您將收到的JAXBElement的實例之一。

演示

package forum13709611; 

import java.io.StringReader; 
import javax.xml.bind.*; 
import javax.xml.transform.stream.StreamSource; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Book.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     String code = "<book><title>Harry Potter</title></book>"; 
     StreamSource source = new StreamSource(new StringReader(code)); 
     JAXBElement<Book> jaxbElement = unmarshaller.unmarshal(source, Book.class); 
    } 

} 

package forum13709611; 

public class Book { 

    private String title; 

    public String getTitle() { 
     return title; 
    } 

    public void setTitle(String title) { 
     this.title = title; 
    } 

}