gpt4 book ai didi

java - 向 JAXB 元素添加属性

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:52 27 4
gpt4 key购买 nike

我正在努力进行一些 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com