简体   繁体   English

映射自定义对象所需的JAXB帮助

[英]JAXB Help needed for mapping Custom Objects

I have XML receiving from some server. 我有从某些服务器接收的XML。 I need to unmarshall that xml to java objects and marshall java objects to xml. 我需要解组该XML到Java对象和将Java对象编组到xml。

How Can i do that?. 我怎样才能做到这一点?。

Below is my XML format. 下面是我的XML格式。

<parent>
    <child>
        <order>
            <row no="1">
                <AB val="ID">205</AB>
                <AB val="NAME">JS</AB>
                <AB val="DETAILS">
                    <prod no="1">
                        <AB val="PRODID">205</AB>
                        <AB val="NAME">Prod1</AB>
                    </prod>
                    <prod no="2">
                        <AB val="PRODID">206</AB>
                        <AB val="NAME">Prod2</AB>
                    </prod>
                </AB>
            </row>
        </order>
    </child>
</parent>

You can use jaxb2-maven-plugin with xjc goal to generate your java classes from xml schema (xsd) during build (you can generate xml schema from xml by any online generator, for example use this ). 您可以使用jaxb2-maven-pluginxjc目标构建过程中生成的XML架构(XSD),Java类(可以通过任何在线发生器从XML生成XML模式,例如使用 )。

You can also just use xjc from console and generate your classes beforehand, it's built in into java (see <your jdk path>/bin/xjc.exe ). 您也可以只从控制台使用xjc并预先生成类,它已内置在Java中(请参见<your jdk path>/bin/xjc.exe )。

Then simply use marshaller/unmarshaller, to do the work, for example: 然后只需使用marshaller / unmarshaller进行工作,例如:

JAXBContext jaxbContext = JAXBContext.newInstance(YourClazz.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
YourClazz yourclazz = (YourClazz) jaxbUnmarshaller.unmarshall(new File("path/to/your/xml"));

btw I suggest caching JAXBContext instances, use Map<Class<?>, JAXBContext> . 顺便说一句,我建议缓存JAXBContext实例,使用Map<Class<?>, JAXBContext> Do not cache marshaller/unmarshaller tho. 不要缓存marshaller / unmarshaller tho。

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

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