java - 具有自定义方案的 JAXB 对象

标签 java jaxb

我想生成这个 XML:

<payment xmlns="http://www.elastic-payments.com/schema/payment">
    <merchant-account-id>1233</merchant-account-id>
    ........
</payment>

我用 JAXB 尝试过:

@XmlRootElement(name = "payment")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(namespace="http://www.elastic-payments.com/schema/payment")
public class AuthorizeRequest { 

    @XmlElement(name = "merchant-account-id")
    public String merchantAccountId;
    ..........
}

但我只得到这个:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<payment>
    <merchant-account-id>1233</merchant-account-id>
</payment>

您知道如何为根标记 payment 设置自定义 xmlns 吗?

最佳答案

Do you know how I can set custom xmlns for the root tag payment?

删除 @XmlType 并在 @XmlRootElement 中添加命名空间。像这样的东西。

    @XmlRootElement(name = "payment", namespace="http://www.elastic-payments.com/schema/payment")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class AuthorizeRequest {

        @XmlElement(name = "merchant-account-id")
        public String merchantAccountId;
        ..........

    }

输出会是这样的,这可能是你不想要的

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:payment xmlns:ns2="http://www.elastic-payments.com/schema/payment">   
   <merchant-account-id>1233</merchant-account-id>
</ns2:payment>

如果要删除此 header ( <?xml version="1.0" encoding="UTF-8" standalone="yes"?> ),请将 JAXB_FRAGMENT 设置为 true。

   JAXBContext jaxbContext  = JAXBContext.newInstance(AuthorizeRequest.class);
   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
   jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); //remove header
   AuthorizeRequest authorizeRequest = new AuthorizeRequest();
   authorizeRequest.setMerchantAccountId("123123");
   //jaxbMarshaller.marshal(authorizeRequest,System.out); //print to console

最后,要删除多余的 ns2,请选择 AuthorizeRequest.class 所在的包并创建 package-info.java 文件并添加以下注释。如果需要,您可以更改它

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.elastic-payments.com/schema/payment", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = { @javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.elastic-payments.com/schema/payment", prefix = "") })
package com.foo.bar;

关于java - 具有自定义方案的 JAXB 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57981730/

相关文章:

java - Java 最优雅的 isNumeric() 解决方案

java - 如何在评级栏中设置 float 类型x.5?

java - 无法将类型 "java.lang.Integer"编码(marshal)为元素,因为它缺少 @XmlRootElement 注释

java - 如何通过jaxb bindings.xml区分重复元素

java - Uri 不是绝对的

java - 弹出堆栈时内存会发生什么情况?

java - 无法替换°字符

java - JAXB键值问题

java - 显示来自 submat 的图像时出现 MattoBitmap 错误

java - 更改 jaxb 中对象的命名空间