java - 向 JAXB 元素添加属性

标签 java xml jaxb

我正在努力进行一些 JAXB 解析,需要一些指导。

本质上,我正在尝试向我已经使用@XmlElement 声明为元素的类变量添加属性。到目前为止,任何使用 @XmlAttribute 的尝试都会在类级别设置属性。

我目前得到的是:

<DataClass newAttribute="test">
  <myElement>I wish this element had an attribute</myElement>
  <anotherElement>I wish this element had an attribute too</anotherElement>
</DataClass>

我想这样做:

<DataClass>
  <myElement thisAtt="this is what I'm talking about">This is better</myElement>
  <anotherElement thisAtt="a different attribute here">So is this</anotherElement>
</DataClass>

我看到其他帖子使用@XmlValue 将属性添加到单个元素,但是当您有元素时这不起作用,并且不会对多个元素起作用。

有没有人想过如何实现这一点?

谢谢! 杰森

最佳答案

这将创建该 XML:

public class JaxbAttributes {
    public static void main(String[] args) throws Exception {
        Marshaller marshaller =
            JAXBContext.newInstance(DataClass.class).createMarshaller();
        StringWriter stringWriter = new StringWriter();
        DataClass dataClass = new DataClass(
               new Foo("this is what I'm talking about", "This is better"),
               new Foo("a different attribute here", "So is this"));
        marshaller.marshal(dataClass, stringWriter);
        System.out.println(stringWriter);
    }

    @XmlRootElement(name = "DataClass")
    @XmlType(propOrder = {"myElement", "anotherElement"})
    static class DataClass {
        private Foo myElement;
        private Foo anotherElement;

        DataClass() {}
        public DataClass(Foo myElement, Foo anotherElement) {
            this.myElement = myElement;
            this.anotherElement = anotherElement;
        }

        public Foo getMyElement() { return myElement; }
        public void setMyElement(Foo myElement) { this.myElement = myElement; }
        public Foo getAnotherElement() { return anotherElement; }
        public void setAnotherElement(Foo anotherElement) { this.anotherElement = anotherElement; }
    }

    static class Foo {
        private String thisAtt;
        private String value;

        Foo() {}
        public Foo(String thisAtt, String value) {
            this.thisAtt = thisAtt;
            this.value = value;
        }

        @XmlAttribute
        public String getThisAtt() { return thisAtt; }
        public void setThisAtt(String thisAtt) { this.thisAtt = thisAtt; }
        @XmlValue
        public String getValue() { return value; }
        public void setValue(String value) { this.value = value; }
    }
}

关于java - 向 JAXB 元素添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6769697/

相关文章:

java - 如何选择一个随机数并保存它?

xml - 使用 XSLT 从另一个 xml 文件获取 XML 节点描述

java - 如何编写具有多个命名空间的正确 XML 以便进行验证?

jaxb - Jersey Jax-RS出现内存错误

java - 从 WSDL 使用 jaxb2-maven-plugin 生成类

java - @javax.persistence.Column(可更新=假)

Java.lang.NoSuchMethodError : org. hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session after update to hibernate 4

java - 找出运行 JVM Eclipse 的设备

php - 使用 CURL 返回 XML 响应

java - 将View类对象作为参数传递给按钮调用的方法(View View )