如何使用javax.xml.bind通过xmlns字段将XML写入POJO?

时间:2018-12-10 14:49:17

标签: java java-8 javax.xml

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

1 个答案:

答案 0 :(得分: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: Namespace annotation not inherited during unmarshalling - regression in JDK 1.8_102?