JAXB“如果一个类具有@XmlElement属性,则它不能具有@XmlValue属性。”

时间:2011-12-15 05:05:38

标签: java xml xml-serialization jaxb

我正在尝试使用JAXB将XML定义为Java对象绑定。一切正常,除非我尝试生成 XML,例如这个

<request>
    Get Price
    <sessionId>read-only</sessionId>
</request>
来自对象的

哪个类定义为

@XmlRootElement(name="request")
public class  Request {

    @XmlValue
    public String getCommandID() { return "Get Price"; };

    @XmlElement
    public String getSessionID() { return "read-only"; };

}

我收到以下异常:

If a class has @XmlElement property, it cannot have @XmlValue property.

如果我将“sessionId”元素更改为属性,一切正常,但我当然希望它成为元素。

我认为JAXB应该非常灵活,我相信我错过了一些明显的东西。

你可以帮忙吗?

2 个答案:

答案 0 :(得分:5)

您要映射的XML文档类型称为“混合内容”。相应的XML模式如下所示:

<xs:element name="request">
    <xs:complexType mixed="true">
        <xs:sequence>
            <xs:element name="sessionId" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

这意味着文本节点可以与元素节点混合出来。虽然转换样本文档的规则看似微不足道,但以下文档也是有效的,规则也不太清楚。

<request>
    Get Price
    <sessionId>read-only</sessionId>
    More Text
</request>

混合文字有其用途,但通常不赞成。首选方法是使用问题中描述的XML属性:

<request sessionId="read-only">Get Price</request>

要了解JAXB如何处理混合文本,请参阅@XmlMixed注释:

答案 1 :(得分:1)

使commandId元素也有问题吗? e.g。

<request>
    <commandId>Get Price</commandId>
    <sessionId>read-only</sessionId>
</request>

@XmlRootElement(name="request")
public class  Request {

    @XmlElement
    public String getCommandID() { return "Get Price"; };  
    // btw, why's this a constant?

    @XmlElement
    public String getSessionID() { return "read-only"; };  
    // and this too?

}