我定义了一个 Book 类,并且想要创建一个 JAXBElement 对象,该对象将包含与 String 对象中的 XML 相对应的信息。
例如,我可以有这样的东西:
String code = "<book><title>Harry Potter</title></book>";
现在,我想从该字符串开始创建一个 JAXBElement。我需要该字符串来执行一些使用 JAXBElement 无法执行的验证。
那么,我可以做我想做的事吗?如果是,怎么办?
谢谢!
索林
最佳答案
如果您使用采用 Class
参数的 unmarshal
方法之一,您将收到 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;
}
}
关于java - 从字符串创建 JAXBElement<Book>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13709611/