如何在没有任何相关信息的情况下通过JAXB封送对象?

yeg*_*256 14 java xml jaxb

我有一个对象value,它是某种类型的,无论是@XmlRootElement注释还是不注释.我想把它编组成XML:

String value1 = "test";
assertEquals("<foo>test</foo>", toXml("foo", value1));
// ...
@XmlRootElement
class Bar {
  public String bar = "test";
}
assertEquals("<foo><bar>test</bar></foo>", toXml("foo", new Bar()));
Run Code Online (Sandbox Code Playgroud)

我可以使用JAXB现有设施吗,或者我应该创建一些自定义分析器?

bdo*_*han 23

您可以利用JAXBIntrospector执行以下操作:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBIntrospector;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;

public class Demo {


    public static void main(String[] args) throws Exception {
        Object value = "Hello World";
        //Object value = new Bar();

        JAXBContext jc = JAXBContext.newInstance(String.class, Bar.class);
        JAXBIntrospector introspector = jc.createJAXBIntrospector();
        Marshaller marshaller = jc.createMarshaller();
        if(null == introspector.getElementName(value)) {
            JAXBElement jaxbElement = new JAXBElement(new QName("ROOT"), Object.class, value);
            marshaller.marshal(jaxbElement, System.out);
        } else {
            marshaller.marshal(value, System.out);
        }
    }

    @XmlRootElement
    public static class Bar {

    }

}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,当JAXBElement被编组时,它将使用对应于相应模式类型的xsi:type属性进行限定:

<ROOT 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Hello World</ROOT>
Run Code Online (Sandbox Code Playgroud)

要消除限定条件,您只需将创建JAXBElement的行更改为:

JAXBElement jaxbElement = new JAXBElement(new QName("ROOT"), value.getClass(), value);
Run Code Online (Sandbox Code Playgroud)

这将产生以下XML:

<ROOT>Hello World</ROOT>
Run Code Online (Sandbox Code Playgroud)