简体   繁体   English

Java:从.xml文件填充.xsd生成的类

[英]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: 就像是:

  • XML schema file: MyObject.xsd XML模式文件: MyObject.xsd
  • Java class generated from schema: MyObject.java 从模式生成的Java类: MyObject.java
  • XML that matches the schema: MyObject.xml 与架构匹配的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM