0

这是一个示例 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?

4

1 回答 1

0

您有几种选择:

  1. 在文件中定义命名空间package-info.java
@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED,
        namespace = "http://your-namespace.org/")
package org.your_namespace;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
  1. 在所有 XML 元素注释中显式定义命名空间:
@XmlRootElement(name = "sourceSets", namespace = "http://your-namespace.org/")
public class SourceSets {
    @XmlElement(required = true, namespace = "http://your-namespace.org/")
    protected List<SourceSet> sourceSet;
}

相关问题:JAXB:解组期间未继承命名空间注释 - JDK 1.8_102 中的回归?

于 2018-12-10T17:18:03.953 回答