import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class FormatXml {
public static String Fxml(List<HashMap<String, Object>> list) {
Document document = new Document();
List<Map<String, Object>> listInfo = new ArrayList<Map<String, Object>>();
if (list != null && !list.isEmpty()) {
Element el = new Element("DTS"); // 根节点
for (Map<String, Object> e : list) {
Element item = new Element("Item");
for (Map.Entry<String, Object> b : e.entrySet()) {
String key = b.getKey();
String value = (String) b.getValue();
item.setAttribute(key, value);
}
el.addContent(item);
}
document.addContent(el);
}
String xml = getDocument(document);
return xml;
}
public static String getDocument(Document doc) {
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8,解决中文问题
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
xmlout.output(doc, bo);
} catch (IOException e) {
e.printStackTrace();
}
return bo.toString();
}
package com.huawei.io;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.huawei.util.StringUtil;
import java.io.File;
import java.util.*;
public class XmlUtil {
public static void main(String[] args) {
String path = "H://Noname1.xml";
XmlUtil xu = new XmlUtil();
List<HashMap<String, Object>> list = xu.getValue(path);
String str=FormatXml.Fxml(list);
System.out.println(str);
}
// 获取一个Document对象
private Element getRoot(Document doc) {
Element el = null;
try {
el = doc.getRootElement();
} catch (Exception e) {
System.out.println("获取根节点失败...");
}
return el;
}
public List<HashMap<String, Object>> getValue(String path) {
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
SAXReader sax = new SAXReader();
Document doc = null;
Element root = null;
try {
doc = sax.read(new File(path));
root = doc.getRootElement(); // 获取根节点
Iterator iter = root.elementIterator("poson");// 获取根节点下的子节点(一个节点下有多个元素)
while (iter.hasNext()) {
// 获取节点
Element value = (Element) iter.next(); // 获取当前一个 poson
Iterator d = (Iterator) value.elementIterator();
HashMap<String, Object> map = new HashMap<String, Object>();
while (d.hasNext()) {// 获取节点下元素
Element el = (Element) d.next();
String key = el.getName(); // 获取节点名称
String noteValue = el.getText();
map.put(key, noteValue);
// System.out.println(key + " " + noteValue);
}
list.add(map);
}
} catch (DocumentException e) {
e.printStackTrace();
}
return list;
}
}
}