如何将 xml 属性添加到 jaxb 注释类 XmlElementWrapper? [英] How can I add xml attributes to jaxb annotated class XmlElementWrapper?

查看:37
本文介绍了如何将 xml 属性添加到 jaxb 注释类 XmlElementWrapper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 XmlElementWrapper 注释的类,例如:

I have a class with a XmlElementWrapper annotation like:

...

  @XmlElementWrapper(name="myList")
    @XmlElements({
    @XmlElement(name="myElement") }
    )
    private List<SomeType> someList = new LinkedList();

...这段代码产生像

... This code produces XML like

<myList>
  <myElement> </myElement>
  <myElement> </myElement>
  <myElement> </myElement>
</myList>

到目前为止一切都很好.

so far so good.

但现在我需要向列表标签添加属性以获得像

But now I need to add attributes to the list tag to get XML like

<myList number="2">
  <myElement> </myElement>
  <myElement> </myElement>
  <myElement> </myElement>
</myList>

有没有一种聪明的方法来实现这一点,而无需创建包含代表列表的新类?

Is there a 'smart way to achieve this without creating a new class that contains represents the list?

推荐答案

我为您的问题找到了更好的解决方案.

I got a better solution for your question.

要制作 Xml Java 对象,请使用以下代码:

For making Xml Java object, use the following code:

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name="myList")
public class Root {

    private String number;
    private List<String> someList;

    @XmlAttribute(name="number")
    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @XmlElement(name="myElement")
    public List<String> getSomeList() {
        return someList;
    }

    public void setSomeList(List<String> someList) {
        this.someList = someList;
    } 

    public Root(String numValue,List<String> someListValue) {
        this();
        this.number = numValue;
        this.someList = someListValue;  
    }

    /**
     * 
     */
    public Root() {
        // TODO Auto-generated constructor stub
    }

}

要使用 JAXB 运行上述代码,请使用以下命令:

To run the above code using JAXB, use the following:

   import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.*;

public class Demo {

        public static void main(String[] args) throws Exception {
            List<String> arg = new ArrayList<String>();
            arg.add("FOO");
            arg.add("BAR");
            Root root = new Root("123", arg);

            JAXBContext jc = JAXBContext.newInstance(Root.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.marshal(root, System.out);
        }
}

这将产生以下 XML 作为输出:

This will produce the following XML as the output:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <myList number="123">
        <myElement>FOO</myElement>
        <myElement>BAR</myElement>
    </myList>

我认为这对您更有帮助.

I think this is more helpful you.

谢谢..

这篇关于如何将 xml 属性添加到 jaxb 注释类 XmlElementWrapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆