我正在使用JaxB创建一个我需要发送到政府系统的xml文件。 但是,如果我在xml标记中使用xsi:type atribute,那么系统没有读取我的文件并引发错误。
如何从标记中删除xsi:type atribute?
TestJaxB Class有主要方法。
public class TestJaxB {
public static void main(String[] args) {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(D.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
try{
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
}
catch(PropertyException pex)
{
System.err.println("ERRO HEADER");
jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
}
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
D d = new D();
C c = new C();
c.setAtribC("01984199000100");
c.setAtribA("Atrib A");
d.setA(c);
/*B b = new B();
b.setAtribB("01984199000100");
b.setAtribA("Atrib A");
d.setA(b);*/
jaxbMarshaller.marshal(d, System.out);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A类有两个注释 @XmlSeeAlso({B.class,C.class}) @XmlTransient
CLASS A
@XmlSeeAlso({B.class, C.class})
@XmlTransient
public class A{
private String atribA;
public String getAtribA() {
return atribA;
}
@XmlElement
public void setAtribA(String atribA) {
this.atribA = atribA;
}
}
类B和C扩展了一个类并使用@XmlType(propOrder)
CLASS B
@XmlType(propOrder = {"atribB", "atribA"})
public class B extends A{
private String atribB;
B() {
}
B(String atrib) {
// TODO Auto-generated constructor stub
setAtribB(atrib);
}
public String getAtribB() {
return atribB;
}
@XmlElement
public void setAtribB(String atribB) {
this.atribB = atribB;
}
}
CLASS C
@XmlType(propOrder = {"atribC", "atribA"})
public class C extends A{
private String atribC;
C() {
}
C(String atribC) {
setAtribC(atribC);
}
public String getAtribC() {
return atribC;
}
@XmlElement
public void setAtribC(String atribC) {
this.atribC = atribC;
}
}
@XmlRootElement(name="MainTag")
public class D {
private A a;
@XmlElement
public void setA(A a) {
this.a = a;
}
public A getA() {
return a;
}}
使用xsi属性
结果 <?xml version="1.0" encoding="UTF-8" ?>
<MainTag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="">
<a xsi:type="c">
<atribC>01984199000100</atribC>
<atribA>Atrib A</atribA>
</a>
</MainTag>
Tnks和最好的问候!