我无法让@XmlValue 正常工作,因为我一直都在使用NullPointerException — 不知道为什么。我想出了类似下面的东西。
完全删除您的Bar 类,因为您希望它能够包含任何东西,您可以简单地用Object 表示它。
@XmlRootElement(name = "foo", namespace = "http://test.com")
@XmlType(name = "Foo", namespace = "http://test.com")
public class Foo {
@XmlElement(name = "bar")
public List<Object> bars = new ArrayList<>();
public Foo() {}
}
如果不告诉 JAXB 你的类型正在使用哪些命名空间,foo 内的每个 bar 元素将包含单独的命名空间声明和内容——package-info.java 和所有命名空间内容仅用于幻想 目的仅限。
@XmlSchema(attributeFormDefault = XmlNsForm.QUALIFIED,
elementFormDefault = XmlNsForm.QUALIFIED,
namespace = "http://test.com",
xmlns = {
@XmlNs(namespaceURI = "http://test.com", prefix = ""),
@XmlNs(namespaceURI = "http://www.w3.org/2001/XMLSchema-instance", prefix = "xsi"),
@XmlNs(namespaceURI = "http://www.w3.org/2001/XMLSchema", prefix = "xs")})
package test;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
运行这个简单的测试会输出类似于你的 XML sn-p 的东西。
public static void main(String[] args) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Foo.class);
Foo foo = new Foo();
foo.bars.add("a");
foo.bars.add("b".getBytes());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(foo, System.out);
}
输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://test.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<bar xsi:type="xs:string">a</bar>
<bar xsi:type="xs:base64Binary">Yg==</bar>
</foo>