How to set the value of root element using JaxB

Viewed 375

After creating the XML using JAXB, not able to get the value of @XmlRootElement in an expected way using @XmlElement or @XmlAttribute.

Code 1

@XmlRootElement(name = "USER_ID")
@XmlAccessorType(XmlAccessType.NONE)
public class UserD {

    @XmlElement(name = "USER_ID")
    private String userId;
    
    @XmlElement(name = "Name")
    private ArrayList<Name> name;

Output

<USER_ID>
            <USER_ID>1</USER_ID>
            <Name></Name>
            <Name></Name>
            <Name></Name>
<USER_ID>

Code 2

@XmlRootElement(name = "USER_ID")
@XmlAccessorType(XmlAccessType.NONE)
public class UserD {

    @XmlAttribute(name = "USER_ID")
    private String userId;
    
    @XmlElement(name = "Name")
    private ArrayList<Name> name;

Output 2

<USER_ID USER_ID="1">
            <Name></Name>
            <Name></Name>
            <Name></Name>
<USER_ID>

Required Output

<USER_ID>1
            <Name></Name>
            <Name></Name>
            <Name></Name>
<USER_ID>
1 Answers

use the @XmlMixed annotation to use the values with xml elements.

@XmlRootElement(name = "USER_ID")
@XmlAccessorType(XmlAccessType.NONE)
public class UserD {

    @XmlMixed
    private List<String> userId;
    
    @XmlElement(name = "Name")
    private ArrayList<Name> name;

    //getter and setters
}

output

<USER_ID>1
    <Name></Name>
    <Name></Name>
    <Name></Name>
<USER_ID>

Edited

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

add the new line character (\n) to end of the value as follows

userId.add("1\n")
Related