maven依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
private static Map<String, String> anaylisXml(String xmlStr) throws Exception {
Document document = DocumentHelper.parseText(xmlStr);
Map<String, String> resultMap = new HashMap<String, String>();
org.dom4j.Element root = document.getRootElement();
// 获取root节点下的子节点,参数为节点的name
root.element("");
// 获取root节点下的所有子节点集合,返回Iterator,方便遍历
root.elementIterator();
// 获取root节点下的特定节点集合,返回List,方便遍历
root.elements("");
for (Iterator<?> i = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
String name = element.getName();
String value = element.getStringValue();
resultMap.put(name, element.getTextTrim());
}
return resultMap;
}
private static Map<String, String> anaylisXml(String xmlUrl) throws Exception {
Map<String, String> resultMap = new HashMap<String, String>();
SAXReader reader = new SAXReader();
Document document = reader.read(new File(xmlUrl));
org.dom4j.Element root = document.getRootElement();
// 获取root节点下的子节点,参数为节点的name
root.element("");
// 获取root节点下的所有子节点集合,返回Iterator,方便遍历
root.elementIterator();
// 获取root节点下的特定节点集合,返回List,方便遍历
root.elements("");
for (Iterator<?> i = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
String name = element.getName();
String value = element.getStringValue();
resultMap.put(name, element.getTextTrim());
}
return resultMap;
}
写
public static void toXmlByDOM4J(String xmlPath){
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("empnames");
Element empName = rootElement.addElement("empname");
empName.setText("xie");
Element empAge = rootElement.addElement("age");
empAge.setText("25");
Element empTitle = rootElement.addElement("title");
empTitle.setText("软件开发");
//写入文档
writerDocumentToNewFile(document,xmlPath);
String documentStr = document.asXML();
System.out.println(documentStr);
}
private static void writerDocumentToNewFile(Document document,String xmlPath) {
try {
OutputFormat xmlFormat = new OutputFormat();
xmlFormat.setEncoding("UTF-8");
xmlFormat.setNewlines(true);
xmlFormat.setIndent(" ");
FileWriter fileWriter = new FileWriter(new File(xmlPath));
XMLWriter xmlWriter = new XMLWriter(fileWriter,xmlFormat);
xmlWriter.write(document);
xmlWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}