gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:31:02 24 4
gpt4 key购买 nike

我想生成这个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com