Automatic XmlRootElement wrapper for list

2020-07-18 04:38发布

I have a simple class that I needed to marshall. The class is declared as:

@XmlRootElement  
public class XMLUser...

Here's what I get:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xmlUser>
    <login>myLogin</login>
    <password>myPass</password>  
    <role name="role1"/>  
    <role name="role2"/>  
    <role name="role3"/>  
</xmlUser>

Now I want to have multiple users in one file but without the need to create a wrapper class myself, sort of like using @XmlElementWrapper but for a class instead of a field. I don't know if this is possible.

So that I could marshall a List (or some object provided by jaxb) and I could end up with an xml like this (the <users> tag generated automatically):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
    <xmlUser>
        <login>login1</login>
        <password>pass2</password>
        <role name="role1"/>
        <role name="role2"/>
    </xmlUser>
    <xmlUser>
        <login>login2</login>
        <password>pass2</password>
        <role name="role1"/>
        <role name="role3"/>
    </xmlUser>
</users>

Any help is appreciated.

标签: java xml jaxb
1条回答
够拽才男人
2楼-- · 2020-07-18 05:04

It's impossible without creating of new class.
single way is

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Users 
{
   @XmlElement(name = "xmlUsers")
   List<XmlUser> users = new ArrayList<XmlUser>();
}  

output

<users>
    <xmlUsers>
       //...
    </xmlUsers>
    <xmlUsers>
       //...
    </xmlUsers>
</users>
查看更多
登录 后发表回答