Sor*_*aru 2 java xml jax-rs jaxb
我定义了一个 Book 类,我想创建一个 JAXBElement 对象,该对象将包含与来自 String 对象的 XML 对应的信息。
例如,我可以有类似的东西:
String code = "<book><title>Harry Potter</title></book>";
Run Code Online (Sandbox Code Playgroud)
现在,我想从该字符串开始创建一个 JAXBElement。我需要该字符串来执行一些使用 JAXBElement 无法执行的验证。
那么,我可以做我想做的吗?如果是,如何?
谢谢!
索林
如果您使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
书
package forum13709611;
public class Book {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3787 次 |
| 最近记录: |