我正在使用带有m2e的Eclipse Oxygen,以便从模式生成Java类。 如果命名空间与模式匹配,我可以解组符合该模式的xml文件。
如何解组已知符合该架构的xml文件但是在未更改生成的xml等效Java源文件的情况下错过了命名空间声明?
架构:
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://testJaxbUnmarshaller.ngong.eu/0_0_1"
xmlns:tju="http://testJaxbUnmarshaller.ngong.eu/0_0_1"
elementFormDefault="qualified">
<element name="A" type="tju:A" />
<complexType name="A">
<all>
<element name="B" type="tju:B" />
</all>
</complexType>
<complexType name="B">
<attribute name="name" type="string"/>
</complexType>
</schema>
生成A.java:
package eu.ngong.testJaxbUnmarshaller.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "A", propOrder = {
})
public class A {
@XmlElement(name = "B", required = true)
protected B b;
public B getB() {
return b;
}
public void setB(B value) {
this.b = value;
}
}
生成B.java:
package eu.ngong.testJaxbUnmarshaller.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "B")
public class B {
@XmlAttribute(name = "name")
protected String name;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
}
运行正常的xml文件:
<A xmlns="http://testJaxbUnmarshaller.ngong.eu/0_0_1">
<B name="thisIsB"/>
</A>
xml文件导致错误“线程中的异常”主“java.lang.NullPointerException”,我喜欢绕过它,告诉unmarshaller这将被处理,好像一个名称空间已被声明或告诉忘了关于命名空间的任何事情。
<A>
<B name="thisIsB"/>
</A>
守则:
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource(xmlFile);
JAXBElement<A> je = unmarshaller.unmarshal(xml, A.class);
A a = (A)(je.getValue());
System.out.println("the name: " + a.getB().getName());