[英]Java: Populating .xsd-generated class from .xml file
I have a class that was generated from an .xsd file, and I have an .xml file that contains data that adheres to the schema in the .xsd. 我有一个从.xsd文件生成的类,并且我有一个.xml文件,其中包含遵守.xsd中架构的数据。 Something like:
就像是:
MyObject.xsd
MyObject.xsd
MyObject.java
MyObject.java
MyObject.xml
MyObject.xml
Is there an easy way for me to deserialize MyObject.xml
into an instance of MyObject.java
? 有一个简单的办法,我反序列化
MyObject.xml
到的实例MyObject.java
? I'm hoping for something easier than hand-walking through the DOM elements and setting all the properties on the object. 我希望比手动遍历DOM元素并设置对象的所有属性更简单。
Basically, I'm looking for the functionality in java.beans.XMLDecoder
, but since my .xml file was not created from the XMLEncoder
, I do not believe that I can use the decoder. 基本上,我正在
java.beans.XMLDecoder
寻找功能,但是由于不是从XMLEncoder
创建我的.xml文件,所以我不相信可以使用解码器。
First you need to create a JAXBContext
instance using the static newInstance
method. 首先,您需要使用静态
newInstance
方法创建一个JAXBContext
实例。 Then create an Unmarshaller
instance using the createMarshaller
method and call the appropriate unmarshal
method on that instance: 然后使用
createMarshaller
方法创建一个Unmarshaller
实例,并在该实例上调用适当的unmarshal
方法:
InputStream is = new FileInputStream("MyObject.xml");
JAXBContext jc = JAXBContext.newInstance(MyObject.class);
Unmarshaller u = jc.createUnmarshaller();
MyObject o = (MyObject)u.unmarshal(is);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.