我有一类大致如下的形状:
@XmlRootElement("foo")
public class Foo {
@XmlElement
public Integer b;
@XmlElement
public Integer a;
}
我现在注意到,JAXB显然指定了Foo
被序列化为<foo><a>123</a><b>456</b></foo>
或<foo><b>456</b><a>123</a></foo>
的状态(并且取决于JVM反射实现的细节)。这使得很难在每次应该产生相同结果的自动测试中比较输出。
我尝试添加
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
上课。起初这似乎很好用,但是现在解组器拒绝解析由旧代码 编写的数据。
是否有一种方法可以使JAXB以确定的顺序进入输出子元素,但在其输入中接受任何顺序?
编辑:这实际上可能不是JAXB问题,但底层XML解析器之一比应有的选择更具挑剔性。我得到的潜在异常是
org.xml.sax.SAXParseException; lineNumber: 59; columnNumber: 16; cvc-complex-type.2.4.d: Invalid content was found starting with element 'a'. No child element is expected at this point.
答案 0 :(得分:1)
您可以使用@XmlType
和propOrder
定义顺序,如下所示:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement("foo")
@XmlType(name = "", propOrder = {
"a",
"b"
})
public class Foo {
@XmlElement
public Integer b;
@XmlElement
public Integer a;
}
这是我的JAXB配置:
//Prepare JAXB objects
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Unmarshaller u = jc.createUnmarshaller();
//Create an XMLReader to use with our filter
XMLReader reader = XMLReaderFactory.createXMLReader();
//Prepare the input, in this case a java.io.File (output)
InputStream stream = new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8));
Reader isr = new InputStreamReader(stream, "UTF-8");
InputSource is = new InputSource(isr);
//Create a SAXSource specifying the filter
SAXSource source = new SAXSource(is);
//Do unmarshalling
ret = (Foo) u.unmarshal(source);