【问题标题】:JAXB using the value of variable as XML tagJAXB 使用变量的值作为 XML 标记
【发布时间】:2014-05-23 20:23:08
【问题描述】:

你的问题很简单,但我没有发现其他人有同样的问题。 我正在尝试使用 JAXB 创建 XML,所以 我有课:

@XmlRootElement
public class Container{
private String name;
private String value;

public Container(String name, String value){
    this.name = name;
    this.value = value;
  }
}

使用元帅:

公开课演示{

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Container.class);

    Container container = new Container("potatoes","5");


    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(container, System.out);
  }
 }

我收到的输出是:

<Container>
<name>potatoes</name>
<value>5</value>
 </Container>

有没有类似的输出方式:

<Container>
<potatoes>5</potatoes>
</Container>

使用 JAXB?

【问题讨论】:

  • 你想要的输出...potatoes = 5 and value = 5。(5正在重复)。这没有多大意义。一个标签通常会在其中包含一些信息....可能是您需要重新考虑您的需求/设计,或者您可能给出了错误的示例。
  • 这是一个例子。我当然想做一些更有意义的事情。不过我调整了这个例子:)

标签: java jaxb


【解决方案1】:

您可以使用带有 @XmlAnyElement 注释的属性并将元素作为 JAXBElement 返回:

@XmlAnyElement
public JAXBElement<String> getThing() {
    return new JAXBElement<String>(new QName(this.name), String.class, this.value);
}

【讨论】:

  • 我会在星期一试一试。非常感谢您的回答。
  • 请记住,反向(xml -> 对象)是不可能的
  • 感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多