Unmarshall MixedContent with Jaxb returns 具有空变量的对象

Unmarshall MixedContent with Jaxb returns Objects with null variables

我想解组一个 XML- 包含混合内容的文件。我在 Whosebug 上找到了一个似乎合适的线程 (JAXB- @XmlMixed usage for reading @XmlValue and @XmlElement),其中用户 bdoughan 定义了 3 个用例来处理混合内容。

第三个用例将标签之间的文本保存在单个字符串变量中,并将元素保存在列表中。这就是我想要的。不幸的是我无法让它工作并且线程很旧并且可能已经过时了。

我已经用一个对象列表和一个我的参考列表尝试了用例 #3 Class。我还尝试了@XmlElement 和@XmlValue 注释。

我在 2.3.1 版的 javax.xml.bind jaxb-api 和 [=30] 的 Maven 项目中使用 2.3.1 版的 org.glassfish.jaxb jaxb-runtime =] SE 版本 12.0.2.

我用

测试的示例 XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Date>
    2018.06.27
    <reference id="AnyId1">
    </reference>
</Date>

我的Class代表

@XmlRootElement(name="Date")
public class TestPojo {

@XmlMixed
public String getTextContent() {
    return textContent;
}

public void setTextContent(String textContent) {
    this.textContent = textContent;
}

@XmlElementRef(name="reference", type = Reference.class)
public List<Object> getRef() {
    return ref;
}

public void setRef(List<Object> ref) {
    this.ref = ref;
}

String textContent;
List<Object> ref = new ArrayList<Object>();

}    

我希望 xml 被解组为 POJO 对象并分配正确的值。对象变量(textContent 和 ref)在解组后为空。

你可以试试这个:

使用如下参考 class,

@XmlAccessorType(XmlAccessType.FIELD)
public class Reference {
    @XmlAttribute
    private String id;
}

还有你的根 class,

@XmlRootElement(name="Date")
public class TestPojo {

    @XmlMixed
    @XmlAnyElement
    private List<Object> textContent;

    @XmlElement
    private Reference reference;

}

这将解组为您提供参考元素和列表中的所有其他内容。

对于您的示例,它将有 2 个条目。日期 value/text 以及制表符 (\t) 和换行符 (\n),以及另一个带有换行符的条目。

所以你可以使用这个列表来处理内容并使用你想要的。

如果有更清洁的解决方案,我很感兴趣。干杯

更新回复评论:

为了更清楚地修复。我所做的是使用 @XmlElement 而不是 @XmlElementRef 作为单个参考而不是列表(因为这是我在 xml 中看到的)。

我还为混合内容添加了 @XmlAnyElement 注释,使其成为一个列表。这就是修复它的原因。所以坚持你的 class,它看起来像下面这样:

@XmlRootElement(name="Date")
public class TestPojo {

    List<Object> textContent;
    Reference ref;

    @XmlMixed
    @XmlAnyElement
    public List<Object> getTextContent() {
        return textContent;
    }

    public void setTextContent(List<Object> textContent) {
        this.textContent = textContent;
    }

    @XmlElement(name="reference")
    public Reference getRef() {
        return ref;
    }

    public void setRef(Reference ref) {
        this.ref = ref;
    }

}

@XmlAccessorType 节省了我编写 getter 和 setter 的时间。有关此注释对示例的作用的解释(以及与 @XmlElement 相关的内容,请查看: