0
public class RequestXml // this pojo for RequestXML
{
    private Contact[] Contact;

    public Contact[] getContact ()
    {
        return Contact;
    }

    @XmlElement(name="Contact")
    public void setContact (Contact[] Contact)
    {
        this.Contact = Contact;
    }
}

另一个pojo

public class Contact  // this class is for contact
{
    private String content;
    private String role;

    public String getContent ()
    {
        return content;
    }

    @XmlElement(name="content")
    public void setContent (String content)
    {
        this.content = content;
    }   

    public String getRole ()
    {
        return role;
    }

    @XmlElement(name="role")
    public void setRole (String role)
    {
        this.role = role;
    }
}

当我在编组时得到如下结果

<Contact role="firstUser"/>
<Contact role="secondUser"/>
<Contact role="LastUser"/>

如下是预期的输出:

<Contact role="firstUser">aaaa</Contact>
<Contact role="secondUser">bbbb</Contact>
<Contact role="LastUser">cccc</Contact>

请帮助我。

4

1 回答 1

0

要将字段编组为内容,请使用@XmlValue注释。要将其编组为属性,请使用@XmlAttribute. 这是ContractPOJO 的样子,以及我的测试:

@XmlRootElement
public class RequestXml {
    private Contact[] contact;

    @XmlElement(name = "Contact")
    public Contact[] getContact() {
        return contact;
    }

    public void setContact(Contact[] Contact) {
        this.contact = Contact;
    }
}

public class Contact {
    private String content;
    private String role;

    public Contact(String content, String role) {
        this.content = content;
        this.role = role;
    }

    @XmlValue
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @XmlAttribute
    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}

考试:

public class JaxbTest {

    @Test
    public void testObjectToXml() throws JAXBException {
        RequestXml requestXml = new RequestXml();
        requestXml.setContact(new Contact[]{new Contact("aaa", "bbb")});
        JAXBContext jaxbContext = JAXBContext.newInstance(RequestXml.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(requestXml, System.out);
    }
}

这提供了以下输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<requestXml>
    <Contact role="bbb">aaa</Contact>
</requestXml>

编辑:另外,请参阅在字段之前和 getter 声明之前使用 @XmlElement 有什么区别?对于注释 getter/setter 和字段的区别。

于 2018-11-27T11:56:48.447 回答