我正在尝试使用JAXB构建具有如下结构的复杂xml文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xc:XCache xmlns:xc="xCache" xc:action="Action">
<xc:XCacheArea xc:value="SomeParameters">
<sp:nickName xc:value="value" xmlns:sp="test.SomeParameters">
</xc:XCacheArea>
</xc:XCache>
但是,我尝试应用某些名称空间的深度越大,实现它的难度就越大。
我得到的结果如下:
<xc:XCache xmlns:xc="XCache" xmlns:mp="SomeParameters" xc:action="Action">
<xc:XCacheArea xc:value="SomeParameters">
<sp:nickName/>
</xc:XCacheArea>
很明显,JAXB将根目录元素xmlns:mp="SomeParameters"
注入到根元素中,这是不希望的。
我的代码:
App.class
public class App {
public static void main(String[] args) {
App app = new App();
app.run();
}
private void run() {
XCache cache = new XCache();
cache.setAction("Action");
cache.setxCacheArea(new XCacheArea("SomeParameters", new NickName()));
try {
JAXBContext jaxbContext = JAXBContext.newInstance(XCache.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(cache, new File("test.xml"));
} catch (Exception e) {
e.printStackTrace();
}
}
NickName.class
public class NickName {
private String value;
}
nickname \ package-info.java
@XmlSchema(namespace = "SomeParameters",
elementFormDefault = XmlNsForm.QUALIFIED,
attributeFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(prefix = "sp", namespaceURI = "SomeParameters")
})
package com.utils.collection.xml.nickname;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
xcache \ package.info.java
@XmlSchema(namespace = "XCache",
elementFormDefault = XmlNsForm.QUALIFIED,
attributeFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(prefix = "xc", namespaceURI = "XCache")
})
package com.utils.collection.xml.xmlcache;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
XCache.class
@XmlRootElement(namespace = "XCache", name = "XCache")
public class XCache {
private String action;
private XCacheArea xCacheArea;
public XCacheArea getxCacheArea() {
return xCacheArea;
}
@XmlElement(namespace = "XCache", name = "XCacheArea")
public void setxCacheArea(XCacheArea xCacheArea) {
this.xCacheArea = xCacheArea;
}
public String getAction() {
return action;
}
@XmlAttribute(name = "action", namespace = "XCache")
public void setAction(String action) {
this.action = action;
}
}
XCacheArea.class
public class XCacheArea {
private String value;
private NickName nickName;
public NickName getNickName() {
return nickName;
}
@XmlElement(name = "nickName", namespace = "SomeParameters")
public void setNickName(NickName nickName) {
this.nickName = nickName;
}
public String getValue() {
return value;
}
@XmlAttribute(name = "value", namespace = "XCache")
public void setValue(String value) {
this.value = value;
}
}
编辑:项目结构