另外,這種使用情況下,可以很容易地用JAXB實現處理( Metro,EclipseLink MOXy,Apache JaxMe等):
域
package com.example;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Domain
{
private String type;
private String os;
@XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
}
包信息
@XmlSchema(xmlns={
@XmlNs(
prefix="qemu",
namespaceURI="http://libvirt.org/schemas/domain/qemu/1.0")
})
package com.example;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;
演示
package com.example;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Domain.class);
Domain domain = new Domain();
domain.setType("kvm");
domain.setOs("linux");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(domain, System.out);
}
}
輸出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<domain xmlns:qemu="http://libvirt.org/schemas/domain/qemu/1.0" type="kvm">
<os>linux</os>
</domain>
更多信息
不錯,謝謝!好的,但仍然有一個問題:我不希望該qemu前綴作爲所有節點的默認前綴。它應該只在根節點內部定義,以便生成的XML看起來完全像我的問題。你有什麼提示如何實現這一點? – ifischer 2011-05-25 08:16:21
@ifischer我不認爲有一種方法來獲得您的確切輸出。您可以嘗試刪除'setDefaultPrefix'語句,但這也會從xmlns聲明中刪除qemu。爲什麼你需要在你的輸出中輸入qemu,如果你不打算用它作爲你的元素的前綴? – dogbane 2011-05-25 08:29:10
,因爲並非所有子節點都使用qemu名稱空間。另外,也許我想稍後添加更多的XML名稱空間。順便說一句,生成的XML需要採用非常特定的格式,因爲它已發送到非常嚴格的Libvirt。 – ifischer 2011-05-25 08:35:47