如何使用JAXB将以下xml转换为java对象 [英] How do I convert the following xml into java objects using JAXB

查看:105
本文介绍了如何使用JAXB将以下xml转换为java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将此XML转换为Java对象的最佳方法是什么?

What is the best way to convert this XML into Java objects?

<entity>         
    <customers id=2 other="data">
        <customer name="john">testData1</customer>
        <customer name="jenny">testData2</customer>
        <customer name="joe">testData3</customer>
        <customer name="joanna">testData4</customer>
    </customers>
</entity>

最好使用带有HashMap的自定义XMLAdapter来转换<$ c $的多个xml行c>< customer> ?
我不确定XMLAdapter是否适用于此场景。任何想法都将不胜感激。

Is it best to use a custom XMLAdapter with a HashMap to convert multiple xml rows of <customer>?
I'm not sure if the XMLAdapter is the proper use case for this scenario. Any ideas would be appreciated.

推荐答案

在我看来,最佳方法是编写一个xsd文件来验证你的xml 。您可以使用它与使用Java捆绑的xjc生成Java类。这应该可以帮到那里。

Best approach, in my opinion, would be to write an xsd file to validate against your xml. You can use that to generate your java classes using xjc which comes bundled with Java. This should get you there.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:NameOfNamespace="http://enter.your.namespace.here"
        targetNamespace="http://enter.your.namespace.here"
        attributeFormDefault="unqualified"
        elementFormDefault="qualified">

    <complexType name="customer">
        <simpleContent>
            <extension base="string">
                <attribute name="name"/>
            </extension>
        </simpleContent>
    </complexType>

    <complexType name="customers">
        <sequence>
            <element name="customer" type="NameOfNamespace:customer"/>
        </sequence>
        <attribute name="id" type="positiveInteger"/>
        <attribute name="other"/>
    </complexType>

    <complexType name="entity" >
        <sequence>
            <element name="customers" type="NameOfNamespace:customers" minOccurs="1" maxOccurs="1"/>
        </sequence>
    </complexType>

    <element name="entity" type="NameOfNamespace:entity"/>
</schema>

打开命令提示符到你放置xsd文件的文件夹,然后生成你需要的java代码只需输入:

Open a command prompt to the folder where you put your xsd file, and then generate java code you'll just need to type:

$ xjc nameOfSchemaFile.xsd

假设你的java'bin'文件夹在你的路径中。生成的类将在与targetNamespace同名的文件夹中创建。

assuming your java 'bin' folder is in your path. The classes generated will be created in folder with the same name as your targetNamespace.

使用这些类可以按照Naimish示例中的说明 JAXB Hello World示例

Using these you can follow the instructions in Naimish's example JAXB Hello World Example

这篇关于如何使用JAXB将以下xml转换为java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆