将属性添加到JAXB元素

Jas*_*onH 8 java xml jaxb

我正在努力解决一些JAXB问题并需要一些指导.

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

我目前得到的是这样的:

<DataClass newAttribute="test">
  <myElement>I wish this element had an attribute</myElement>
  <anotherElement>I wish this element had an attribute too</anotherElement>
</DataClass>
Run Code Online (Sandbox Code Playgroud)

我想这样做:

<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>
Run Code Online (Sandbox Code Playgroud)

我已经看到其他帖子使用@XmlValue向单个元素添加属性,但是当你有Elements时它不起作用,并且不能在多个元素上工作.

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

谢谢!贾森

Rya*_*art 5

这将创建该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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我的foo欠你的债。非常感谢。我没有想过以这种方式使用它,它是基本的面向对象,但由于某种原因我没有看到它。再次非常感谢您。 (2认同)