【发布时间】:2011-03-18 09:46:32
【问题描述】:
[随着理解的进展进行了大量编辑]
是否可以让 Spring Jaxb2Marshaller 使用一组自定义的命名空间前缀(或至少尊重架构文件/注释中给出的前缀)而不必使用 NamespacePrefixMapper 的扩展?
这个想法是让一个类与另一个类具有“具有”关系,而另一个类又包含一个具有不同命名空间的属性。为了更好地说明这一点,请考虑以下使用 JDK1.6.0_12 的项目大纲(我可以在工作中得到的最新版本)。我在包 org.example.domain 中有以下内容:
Main.java:
package org.example.domain;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Main {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(RootElement.class);
RootElement re = new RootElement();
re.childElementWithXlink = new ChildElementWithXlink();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(re, System.out);
}
}
RootElement.java:
package org.example.domain;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(namespace = "www.example.org/abc", name="Root_Element")
public class RootElement {
@XmlElement(namespace = "www.example.org/abc")
public ChildElementWithXlink childElementWithXlink;
}
ChildElementWithXLink.java:
package org.example.domain;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
@XmlRootElement(namespace="www.example.org/abc", name="Child_Element_With_XLink")
public class ChildElementWithXlink {
@XmlAttribute(namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(namespace = "http://www.w3.org/1999/xlink", name = "anyURI")
private String href="http://www.example.org";
}
包信息.java:
@javax.xml.bind.annotation.XmlSchema(
namespace = "http://www.example.org/abc",
xmlns = {
@javax.xml.bind.annotation.XmlNs(prefix = "abc", namespaceURI ="http://www.example.org/abc"),
@javax.xml.bind.annotation.XmlNs(prefix = "xlink", namespaceURI = "http://www.w3.org/1999/xlink")
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.example.domain;
运行 Main.main() 给出以下输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Root_Element xmlns:ns1="http://www.w3.org/1999/xlink" xmlns:ns2="www.example.org/abc">
<ns2:childElementWithXlink ns1:href="http://www.example.org"/>
</ns2:Root_Element>
而我想要的是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<abc:Root_Element xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:abc="www.example.org/abc">
<abc:childElementWithXlink xlink:href="http://www.example.org"/>
</abc:Root_Element>
一旦这部分工作正常,问题就会转移到在 Spring(Spring 2.5.6,spring-oxm-tiger-1.5.6 提供 Jaxb2Marshaller)中配置 Jaxb2Marshaller,以便它通过简单的方式提供相同的功能上下文配置和对 marshal() 的调用。
感谢您一直关注这个问题!
【问题讨论】:
-
你能用香草
JAXBContext来解决这个问题,即不涉及 Spring 吗?看起来Jaxb2Marshaller应该与问题无关。另外,您使用的是哪个 JDK 和/或 JAXB 版本? (附:嗨,加里 :) -
嘿,skaffman :-) 根据需要进行了编辑。这是我的疯子。