JAXB (JSR-222)实现在解组时对 XML 元素的顺序非常宽容。我将在下面用一个例子来演示。
根
下面是具有单独List
属性的域对象。
package forum11519412;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
List<String> x;
List<Integer> y;
}
输入.xml
以下是List
混合项目的示例 XML 文档:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<y>1</y>
<x>A</x>
<y>2</y>
<x>B</x>
<y>3</y>
<x>C</x>
</root>
演示
演示代码将解组input.xml
并将其编组。
package forum11519412;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11519412/input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
输出
在生成的 XML 中,内容将按顺序排列。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<x>A</x>
<x>B</x>
<x>C</x>
<y>1</y>
<y>2</y>
<y>3</y>
</root>