XMLRootElement将类转换为XML中的XML

时间:2014-10-13 07:17:01

标签: java rest jaxb jersey jax-rs

我非常擅长将模型类转换为JSON数组或对象。

但就XML而言,我是一个菜鸟。

我希望我的最终输出像这样

<Response>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>
</Response>

为了实现它,我创建了一个模型类

@XmlRootElement(name = "Response")
public class Response {

    private Say say = new Say();

    public Say getSay() {
        return say;
    }

    public void setSay(Say say) {
        this.say = say;
    }

    @XmlRootElement(name = "Say")
    static class Say {

        @XmlAttribute
        private String voice = "alice";

        private String string = "Thanks for trying our documentation. Enjoy!";

        public String getString() {
            return string;
        }

        public void setString(String string) {
            this.string = string;
        }
    }   
}

现在用jersey将其转换为XML后,我的输出是

<Response>
<say voice="alice">
<string>Thanks for trying our documentation. Enjoy!</string>
</say>
</Response>

我有一个额外的字符串标签。我不确定为String设置什么属性,以便它出现在正文中。或者还有其他方法吗?

也是为了说。 'S'没有大写。我怎么能把它写成大写字母?

提前致谢

1 个答案:

答案 0 :(得分:3)

默认情况下,属性和公共字段将映射到元素。您要做的是使用@XmlValue将字段映射到元素的值。

@XmlRootElement(name = "Say")
@XmlAccessorType(XmlAccessType.FIELD)
static class Say {

    @XmlAttribute
    private String voice = "alice";

    @XmlValue
    private String string = "Thanks for trying our documentation. Enjoy!";

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }
} 

请注意@XmlAccessorType(XmlAccessType.FIELD)的使用。这是默认行为并不是双倍的&#34;尝试映射getter和setter定义的属性。或者,您可以将注释放在getter上,并省略@XmlAccessorType

结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Response>
    <say voice="alice">Thanks for trying our documentation. Enjoy!</say>
</Response>

public class ResponseTest {
    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(Response.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        Response response = new Response();
        marshaller.marshal(response, System.out);
    }
}

<强>更新

  

但我能否知道为什么&#39; S&#39;在Say中,即使指定了@XmlRootElement(name = "Say"),它也不是大写的吗?

您需要在属性上使用@XmlElement(name = "Say")指定名称。如果您没有,则默认命名将启动。

@XmlElement(name = "Say")
public Say getSay() {
    return say;
}

XmlRootElement(name = "Say")仅适用于元素用作根元素的情况。例如:

Response.Say response = new Response.Say();
marshaller.marshal(response, System.out);

会给你这个输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>