jaxb实体打印为xml

Cri*_*riu 5 java jaxb

我有一个类,我们称之为用户注释@XmlRootElement,带有一些属性(名称,姓氏等).

我将此类用于REST操作,如application/xml.

客户端将POST用户类,所以我想保留日志中的值.

在jaxb中是否有任何方法将此对象打印为xml

例如:

log.info("Customers sent: "+user.whichMethod());
Run Code Online (Sandbox Code Playgroud)

应该产生这个输出:

Customer sent: 
<user> <name>cristi</name> <surname>kevin</surname> </user>
Run Code Online (Sandbox Code Playgroud)

谢谢.

jav*_*a25 19

您可以将此作为端点可访问的常用方法.

public String toXml(JAXBElement element) {
    try {
        JAXBContext jc = JAXBContext.newInstance(element.getValue().getClass());  
        Marshaller marshaller = jc.createMarshaller();  
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshal(element, baos);
        return baos.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }      
    return "";
}
Run Code Online (Sandbox Code Playgroud)


Cri*_*riu 9

找到:)

public void toXml() {
    try {
        JAXBContext ctx = JAXBContext.newInstance(User.class);
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(this, System.out);
    }
    catch (Exception
            e) {

              //catch exception 
    }
}
Run Code Online (Sandbox Code Playgroud)

称之为:

log.info("Customers sent: "+user.toXml());
Run Code Online (Sandbox Code Playgroud)

  • **永远不要**写一个空的catch-block,即使在一个例子中!例子有一个讨厌习惯,在某些时候变成生产代码,然后我们需要保持这种混乱. (14认同)