如何在java中使用常量属性序列化xml?

时间:2017-02-24 16:01:13

标签: java xml

考虑一个班级:

@XmlRootElement(name="root")
class Dto {
    @XmlElement
    @Xml????("constantValue")
    private String field = "12345";
}

输出应该是

<root>
    <field myAttribute="constantValue">12345</field>
</root>

问题是要使用什么注释而不是Xml????

重要提示

许多示例建议使用@XmlAttribute,但这会导致创建一个这样的包装器:

@XmlRootElement(name="root")
class Dto {
    @XmlElement
    private Wrapper field = new Wrapper("12345");
}

class Wrapper  {
    @XmlElement
    private String field;
    @XmlAttribute        
    private String myAttribute = "constantValue";  

    public Wrapper(String field) {
         this.field = field; 
    }
}

如您所见,属性是常量,因此无需为类中的每个String字段创建包装器。所以@XmlAttribute将属性附加到封闭类,在这种情况下不适合。

1 个答案:

答案 0 :(得分:0)

public class XmlTest { @Test public void rootTest() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Root.class); Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter writer = new StringWriter(); Root root = new Root(new Field("constantValue", "123456")); marshaller.marshal(root, writer); System.out.println("Output: " + writer.toString()); } @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "root") public static class Root { @XmlElementRef(name = "field") Field field; public Root(Field field) { super(); this.field = field; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "field") public static class Field { @XmlAttribute(name = "myAttribute") String myAttribute; @XmlValue String value; public Field(String myAttribute, String value) { super(); this.myAttribute = myAttribute; this.value = value; } } } 是此xml结果的唯一有效解决方案。如果您使用DTO类,则可以轻松映射数据。其他一切都不是jaxb。

{{1}}