【问题标题】:Generate source files from XML从 XML 生成源文件
【发布时间】:2015-12-04 01:26:40
【问题描述】:

我有这样开头的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<interface name="AccountAPING" owner="BDP" version="1.0.0" date="now()" namespace="com.betfair.account.api"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <description>Account API-NG</description>
...

之后是各种块,比如:

<operation name="getDeveloperAppKeys" since="1.0.0">
<description>
    Get all application keys owned by the given developer/vendor
</description>
<parameters>
    <request/>
    <simpleResponse type="list(DeveloperApp)">
        <description>
            A list of application keys owned by the given developer/vendor
        </description>
    </simpleResponse>
    <exceptions>
        <exception type="AccountAPINGException">
            <description>Generic exception that is thrown if this operation fails for any reason.</description>
        </exception>
    </exceptions>
</parameters>
</operation>

........

<simpleType name="Status" type="string">
    <validValues>
        <value name="SUCCESS">
            <description>Sucess status</description>
        </value>
    </validValues>
</simpleType>

........

<dataType name="TimeRange">
    <description>TimeRange</description>
    <parameter name="from" type="dateTime" mandatory="false">
        <description>from, format: ISO 8601)</description>
    </parameter>
    <parameter name="to" type="dateTime" mandatory="false">
        <description>to, format: ISO 8601</description>
    </parameter>
</dataType>

如何使用 maven 生成 Java 代码?我尝试使用“maven-jaxb2-plugin”,但它无法解析这个结构。

请注意

  1. 这是一个 XML 文件,不是 xsd
  2. 我正在使用 Netbeans

【问题讨论】:

标签: java xml maven schema


【解决方案1】:

首先,您需要描述您的 xml 示例的架构 (xsd)。如果没有该模式,您将无法使用 Jaxb。您显示的示例没有架构 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 不是您的 xml 的架构。

您可以使用免费的在线工具从 xml 生成架构,但如果不查看自动架构,您就不能依赖这些工具。

【讨论】:

    【解决方案2】:

    要从模式文件生成 Java 代码,请使用 XJC,请参阅 here。打开一个命令提示符到您放置 xsd 文件的文件夹,然后生成您只需要键入的 java 代码:

    $ xjc nameOfSchemaFile.xsd
    

    xjc 包含在 Java SDK 中。

    【讨论】:

    • 我尝试使用 xjc,但它无法解析 - 很多错误,例如 [ERROR] s4s-elt-invalid: Element 'interface' is not a valid element in a schema document. line 3 of file:/D:/Projects/mavenproject1/src/main/xsd/SportsAPING.xml [ERROR] schema_reference.4: Failed to read schema document 'file:/D:/Projects/mavenproject1/src/main/xsd/SportsAPING.xml', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not &lt;xsd:schema&gt;. line 3 of file:/D:/Projects/mavenproject1/src/main/xsd/SportsAPING.xml
    • 啊,你说你有一个模式文件,它以“.XSD”结尾。你不能用“.XML”文件来做到这一点。您必须先编写一个模式文件。看看W3学校的XML Schema教程
    猜你喜欢
    • 2011-11-29
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多