gpt4 book ai didi

namespaces - jaxb xmlElement 命名空间不起作用

转载 作者:行者123 更新时间:2023-12-04 16:51:56 27 4
gpt4 key购买 nike

一段时间以来,我在向属性添加命名空间时遇到了问题。我的要求是创建 xml,它将在子元素而不是 root 上具有命名空间 uri。我将 jaxb 与 eclipselink moxy、jdk7 一起使用。

<document>
<Date> date </Date>
</Type>type </Type>
<customFields xmlns:pns="http://abc.com/test.xsd">
<id>..</id>
<contact>..</contact>
</customFields>
</document>

Classes are:

@XmlRootElement(name = "document")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"type","date", "customFields"})
public class AssetBean {

@XmlElement(name="Type")
private String type;
@XmlElement(name="Date")


@XmlElement(name = "CustomFields",namespace = "http://api.source.com/xsds/path/to/partner.xsd")
private CustomBean customFields = new CustomBean();

//getters/setters here

}
public class CustomBean {

private String id;
private String contact;
//getter/setter
}
package-info.java
@javax.xml.bind.annotation.XmlSchema (
xmlns = {
@javax.xml.bind.annotation.XmlNs(prefix="pns",
namespaceURI="http://api.source.com/xsds/path/to/partner.xsd")
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED
)
package com.abc.xyz

我跟着这篇文章寻求帮助,但无法得到我正在尝试的东西
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html

谢谢

最佳答案

域模型(根)

在下面的域对象中,我将使用 @XmlElement 为其中一个元素分配一个命名空间。注解。

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

String foo;

@XmlElement(namespace="http://www.example.com")
String bar;

}

演示代码

在下面的演示代码中,我们将创建域对象的实例并将其编码为 XML。

import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);

Root root = new Root();
root.foo = "FOO";
root.bar = "BAR";

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}

}

输出

下面是运行演示代码的输出。我们使用 @XmlElement 分配命名空间的元素注释是正确的命名空间限定,但命名空间声明出现在根元素上。

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:ns0="http://www.example.com">
<foo>FOO</foo>
<ns0:bar>BAR</ns0:bar>
</root>

更多信息
  • http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
  • 关于namespaces - jaxb xmlElement 命名空间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16438692/

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