使用XStreamMarshaller,如何在没有标签名称的情况下显示标签的值

时间:2019-03-27 12:55:32

标签: java xml jaxb

我正在尝试将xml文档编组为以下格式:

<Description language="FR">ceci</Description>
<Description language="AN">this</Description>

但是我得到以下输出:

<Description language="FR">
    <value>ceci</value>
</Description> 
<Description language="AN">
    </value>this</value>
</Description>

这是我尝试的代码:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Description", propOrder = {"value"})
public class Description {

    @XmlValue
    protected String value;

    @XmlAttribute(name = "language", required = true)
    protected Language language;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Language getLanguage() {
        return language;
    }

    public void setLanguage(Language value) {
        this.language = value;
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试一下,

Description.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Description", propOrder = {"value"})
public class Description {

    @XmlValue
    protected String value;

    @XmlAttribute(name = "language", required = true)
    protected String language;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String value) {
        this.language = value;
    }
}

用jaxb编组

File outputFile = new File("output path/fileName.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Description.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

Description description = new Description();
description.setLanguage("FR");
description.setValue("ceci");

jaxbMarshaller.marshal(description, outputFile);

输出(fileName.xml)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<description language="FR">ceci</description>