前言
XML作為輕量級的數據存儲文件,主要擁有以下優點:
- 數據內容和機構完全分離。方便作為源數據的后續操作。
- 互操作性強。大多數純文本的文件格式都具有這個優點。純文本文件可以方便地穿越防火牆,在不同操作系統上的不同系統之間通信。
- 規范統一。XML具有統一的標准語法,任何系統和產品所支持的XML文檔,都具有統一的格式和語法。
- 支持多種編碼。方便了多語言系統對xml數據的處理。
- 可擴展性。XML是一種可擴展的語言,可以根據XML的基本語法來進一步限定使用范圍和文檔格式,從而定義一種新的語言。
由以上優點可以得出xml在開發過程中的用途非常廣泛的結論。我需要把數據轉為xml文件,也是因為其操作相對比較遍歷。
實現
引入jar包
<!-- xml文件生成 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
實現代碼
/**
* @Description 通過數據創建Xml文件
* @param rootName
* @param channelName
* @param fileName
* @param mapItems
* @Return void
* @Author Mr.Walloce
* @Date 2019/9/5 11:59
*/
private void createXml(String rootName, String channelName, String fileName, List<Map<String, String>> mapItems) {
if (mapItems == null) {
return;
}
try {
// 生成一個根節點
Element root = new Element(rootName);
// 生成一個document對象
Document document = new Document(root);
//添加子節點數據
this.buildNodes(root, channelName, mapItems);
Format format = Format.getCompactFormat();
// 設置換行Tab或空格
format.setIndent(" ");
format.setEncoding("UTF-8");
// 創建XMLOutputter的對象
XMLOutputter outputer = new XMLOutputter(format);
// 利用outputer將document轉換成xml文檔
File file = new File(fileName+".xml");
if (!file.exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
outputer.output(document, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
log.error("生成xml失敗");
}
}
/**
* @Description 構建子節點數據
* @param root
* @param channelName
* @param mapItems
* @Return void
* @Author Mr.Walloce
* @Date 2019/9/5 11:56
*/
private void buildNodes(Element root, String channelName, List<Map<String, String>> mapItems) {
Element channel = null;
Element node = null;
for (Map<String, String> mapItem : mapItems) {
channel = new Element(channelName);
for (Map.Entry<String, String> entry : mapItem.entrySet()) {
node = new Element(entry.getKey());
node.setText(entry.getValue());
channel.addContent(node);
}
root.addContent(channel);
}
}
以上參數mapItems為要生成xml文件的數據集,key為xml文件的節點屬性,value則為節點屬性的值。
