这是一个示例 xml 对象,就像我从 API 调用中得到的一样:
<?xml version="1.0" ?>
<sourceSets>
<sourceSet>
<sourceSetIdentifier>1055491</sourceSetIdentifier>
<sourceSetData>...</sourceSetName>
</sourceSet>
<sourceSet>
<sourceSetIdentifier>1055493</sourceSetIdentifier>
<sourceSetData>...</sourceSetName>
</sourceSet>
</sourceSets>
这里是SourceSets.java
:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "sourceSets")
public class SourceSets {
@XmlElement(required = true)
protected List<SourceSet> sourceSet;
// getter, setter
}
SourceSet.java
也在那里,并且经过测试可以正常工作,没问题。
要阅读此内容,我使用:
inputXML = ... // as seen above
public static void main(String[] args) {
InputStream ins = new ByteArrayInputStream(
inputString.getBytes(StandardCharsets.UTF_8));
SourceSets sourceSets = null;
try {
JAXBContext jc = JAXBContext
.newInstance(SourceSets.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
sourceSets = (SourceSets) unmarshaller.unmarshal(is);
} catch (PropertyException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
System.out.println("Length of source sets");
System.out.println(sourceSets.getSourceSet().size());
}
结果输出是:
Length of source sets
2
问题是 xml 实际上带有附加到 sourceSets 对象的命名空间:
<sourceSets xmlns="http://source/url">
现在,如果我尝试运行我的脚本,我会得到UnmarshallException
:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://source/url", local:"sourceSets"). Expected elements are <{}sourceSet>,<{}sourceSets>,<{}subscription>
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:726)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
...
at com.package.testing.SourceManualTest.main(SourceManualTest.java:78)
所以我在注释中SourceSets.java
添加了一个命名空间定义,比如@XmlRootElement
@XmlRootElement(namespace = "http://source/url", name = "sourceSets")
随着这个改变,UnmarshallException
消失了,它再次运行......但现在它没有读入任何 SourceSet 对象:
Length of source sets
0
如何考虑命名空间 xml 标记,但仍将 xml 解析为 POJO?