简体   繁体   English

JaxB自动从XML解析为Java类

[英]JaxB automatic parsing from XML to Java classes

I am new about jaxb. 我是关于jaxb的新手。 My question is the following: using jaxb, is it possible to do automatic mapping from an xml file to a java object? 我的问题如下:使用jaxb,是否可以从xml文件到java对象进行自动映射? Starting from xml file, is there something generate the Java class with annotations jaxb relaitve? 从xml文件开始,是否有东西生成带有注释的Java类jaxb relaitve?

It is indeed possible. 这确实是可能的。 However, you'll need an XSD rather than an XML file. 但是,您需要一个XSD而不是XML文件。 There are tools out there ( Trang , for instance) that can infer an XSD from one or more example XML files. 有一些工具(例如Trang )可以从一个或多个示例XML文件中推断出XSD。

Take into account that generating this XSD with a tool might get you inaccurate results if the XML sample isn't complete, or if the schema can't be fully represented in a single XML file (exclusive elements, etc). 考虑到如果XML样本不完整,或者模式无法在单个XML文件(独占元素等)中完全表示,使用工具生成此XSD可能会导致结果不准确。

Once you have an XSD, use xjc in order to generate the marshaller/unmarshaller classes. 获得XSD后,使用xjc生成marshaller / unmarshaller类。

xjc myxsd.xsd

This will generate the annotated classes that JAXB will use for marshalling/unmarshalling. 这将生成JAXB将用于编组/解组的带注释的类。 Notice you could also have coded these classes yourself. 请注意,您也可以自己编写这些类。 Once you have them, just use them in your code: 有了它们,只需在代码中使用它们:

File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(MyRootElement.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyRootElement element = (MyRootElement) jaxbUnmarshaller.unmarshal(file);

Yes, JAXB automatically does marshalling and unmarshalling but it requires a schema file. 是的, JAXB自动进行marshalling unmarshalling但它需要一个模式文件。 JaxB is used to bind XML with Java objects. JaxB用于将XML与Java对象绑定。 Using the XSD schema file, it does marshalling and unmarshalling. 使用XSD架构文件,它进行编组和解组。 There are few simple ant tasks like XJC that can be used. 很少有像XJC这样的简单蚂蚁任务可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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