将 XML 解析/反序列化为 JavaObjects

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24551144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:54:17  来源:igfitidea点击:

Parsing/Deserialize XML to JavaObjects

javaxmljaxbxsd

提问by Smoki

i started a small new project and i want to deserialize objects from XML.

我开始了一个小的新项目,我想从 XML 反序列化对象。

i created a xsd:

我创建了一个 xsd:

http://pastebin.com/n1pwjRGX

http://pastebin.com/n1pwjRGX

and an example XML File :

和一个示例 XML 文件:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hdb>
    <country code="DE">
        <variableHoliday daysAfterEaster="49" name="PENTECOAST" />
        <fixedHoliday month="JANUARY" day="1" name="NEWYEAR" />
        <region code="sa">
            <fixedHoliday month="APRIL" day="1" name="FUNNYDAY" />
            <variableHoliday daysAfterEaster="0" name="EASTERSUNDAY" />
        </region>
        <region code="ba">
            <variableHoliday daysAfterEaster="12" name="CORPUSCHRISTI" />
        </region>
    </country>
    <country code="US">
        <fixedHoliday month="JULY" day="4" name="INDEPENDENCEDAY" />
    </country>
    <country code="AL">
        <fixedHoliday month="JULY" day="4" name="INDEPENDENCEDAY" />
    </country>
</hdb>

Which should use the xsd and so on.

哪个应该用xsd等等。

So how can i achive the deserialization of these XML to a nice Java-Object Structure?

那么我怎样才能将这些 XML 反序列化为一个很好的 Java 对象结构呢?

Mabe like :

马贝喜欢:

class HDB {
    private HashMap<CountryCode,Country> map;
}

class Country {
    private List<Holiday> list; // or two Lists with <variableHoliday> and <fixedHoliday>
    private List<Region> regions;
}

class Region{
    private List<Holiday> list; // or two Lists with <variableHoliday> and <fixedHoliday>
}

class variableHoliday {
    private String name;
    private int daysAfterEaster;
}
class fixedHoliday {
    private String name;
    private int day;
    private MonthName month; // while MonthName is an enum defined like the enum from XSD
}

Any ideas how to achive that easy?

任何想法如何轻松实现?

I thought of jaxb an tried some stuff, but it seems to me (im a beginner with jaxb) that its hard to achive this XML structure because of maps cant be written like v.

我想到了 jaxb 并尝试了一些东西,但在我看来(我是 jaxb 的初学者)很难实现这种 XML 结构,因为映射不能像 v.

采纳答案by Santosh Joshi

use

xjc your_xsd_name -p packagename 

to generate Pojos, xjc is xml java compiler that comes with jdk.

要生成 Pojos,xjc 是 jdk 自带的 xml java 编译器。

once your classes are generated use jaxb as follows

生成类后,请按如下方式使用 jaxb

JAXB Marshalling

JAXB 编组

    HDB hdb = new HDB(); 
    JAXBContext jaxbContext = JAXBContext.newInstance(HDB.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.marshal(hdb, file);
    jaxbMarshaller.marshal(hdb, System.out);

JAXB Unmarshalling

JAXB 解组

    File file = new File("your xml file");
    JAXBContext jaxbContext = JAXBContext.newInstance(hdb.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    HDB hdb = (HDB) jaxbUnmarshaller.unmarshal(file);
    System.out.println(hdb);

Visit following link for more info JAXB marshalling and unmarshalling

访问以下链接了解更多信息JAXB 编组和解组

回答by kunwar.sangram

JAXB - Java to XML binding, is the way to go for effective and efficient XML to POJO and vice versa as pointed by above example.

JAXB - Java 到 XML 绑定,是有效和高效的 XML 到 POJO 的方法,反之亦然,如上例所示。

Plus required tools are bundled with JDK only requirement is error free XSD/set of XSDs required for creating object bindings.

加上所需的工具与 JDK 捆绑在一起,唯一的要求是创建对象绑定所需的无错误 XSD/XSD 集。

XJC

徐建中

xjc : with either command line args as -p for package name -d for out dir etc. details can be found on xjc man page/refer Online page.

xjc :使用命令行参数作为 -p 表示包名称 -d 表示输出目录等。详细信息可以在 xjc 手册页/参考在线页面上找到

But if implementation involves multiple xsds, then prefer using xjb (binding file)

但是如果实现涉及多个xsds,那么更喜欢使用xjb(绑定文件)

<jxb:bindings xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
              xmlns:xs="http://www.w3.org/2001/XMLSchema"
              xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
              version="2.1" jxb:extensionBindingPrefixes="xjc">
    <jxb:globalBindings>
        <xjc:simple/>
    </jxb:globalBindings>
    <jxb:bindings schemaLocation="schema/xml/xmldsig-core-schema.xsd">
        <jxb:schemaBindings>
            <jxb:package name="org.w3.xmldsig"/>
        </jxb:schemaBindings>
    </jxb:bindings>
    <jxb:bindings schemaLocation="schema/xml/xenc-schema.xsd">
        <jxb:schemaBindings>
            <jxb:package name="org.w3.xenc"/>
        </jxb:schemaBindings>
    </jxb:bindings>
</jxb:bindings>

Comprehensive guide from oracle on XJBs Guide

来自 oracle 的综合指南 XJBs指南

Once you have your bindings generated, all you need is create JAXBContextwith either class or list of packages separated by :

生成绑定后,您只需要创建JAXBContext类或包列表,并用以下符号分隔:

final JAXBContext context = JAXBContext.newInstance(Generated.class);
final JAXBContext contextOnPackage = JAXBContext.newInstance("com.alpha.generated:com.beta.generated");

optionally you can provide a Classloader as well final JAXBContext contextCustomClassLoader = JAXBContext.newInstnace("..:..", X.class.getClassLoader()); // this is for more advanced use.

您可以选择提供一个类加载器以及 final JAXBContext contextCustomClassLoader = JAXBContext.newInstnace("..:..", X.class.getClassLoader()); // 这是为了更高级的使用。

UnMarshalling

解组

// source can be a file/InputStream/InputSource etc.  
Test obj = (Test)context.createUnMarshaller().unmarshal(source);

Marshalling

编组

Test test = gen.xml.package.ObjectFactory.createTest();  
// Bunch of setters   
// gen.xml.package is generated package XJC will create ObjectFactory as well  
// sink can be File/OutputStream/Writer etc.  
context.createMarshaller().marshal(test, sink);

For more details refer to Javadocs and JAXB Specifications.

有关更多详细信息,请参阅 Javadocs 和 JAXB 规范。