[英]jaxb how to marshall values in some order?
fe我想擁有一個XML,其中我的集合的值按字母順序存儲:
<tag1>a</tag1>
<tag1>b</tag1>
<tag1>c</tag1>
jaxb有可能嗎?
謝謝。
在事物的Java方面使用有序集合。
根
tag1
屬性是SortedSet
。 創建TreeSet
時可以傳遞一個Comparator
:
package forum9096805;
import java.util.*;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Root {
private SortedSet<String> tag1 = new TreeSet<String>();
public SortedSet<String> getTag1() {
return tag1;
}
public void setTag1(SortedSet<String> tag1) {
this.tag1 = tag1;
}
}
演示
package forum9096805;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.getTag1().add("b");
root.getTag1().add("c");
root.getTag1().add("a");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
產量
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<tag1>a</tag1>
<tag1>b</tag1>
<tag1>c</tag1>
</root>
問題應該是: 在XSD(XML Schmea)中是否可能? 答案是否定的 。 但是您可以使用List實現或數組等有序集合來確保XML實例按字母順序包含數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.