2012-12-04 44 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; 
    } 

}