1、项目文件结构图:
2、文件代码:
doc.xml
语文 文科 数学 理科 英语 文科
Dom4jMain.java
package Dom4j.Rrhythmk.com;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream.GetField;import java.io.Writer;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.dom4j.DocumentHelper;public class Dom4jMain { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\" + "\\xml\\Doc.xml"; System.out.println(path); ReadXML(path); StringToXML(); } /* * 读取XML */ public static void ReadXML(String path) { try { InputStream inputStream = new FileInputStream(new File(path)); SAXReader saxRD = new SAXReader(); Document doc = saxRD.read(inputStream); Element element = doc.getRootElement(); System.out.println("getNamespace:" + element.getNamespace()); System.out.println("节点名称-getName:" + element.getName()); System.out.println("getText:" + element.getText()); IteratorbookList = element.elements("Book").iterator(); while (bookList.hasNext()) { Element nextElement = bookList.next(); System.out.println(nextElement.attribute("id").getText()); System.out .println(nextElement.element("Name").getStringValue()); System.out .println(nextElement.element("Type").getStringValue()); } } catch (Exception e) { e.printStackTrace(); } } /* * 字符串转换XML * 修改XML节点 * 保存XML * */ public static void StringToXML() { try { // 1、字符串转换XML System.out.println("StringToXML-字符串转换成XML对象"); String xmlStr = " "; Document doc = DocumentHelper.parseText(xmlStr); Element rootElement = doc.getRootElement(); List 语文 文科 数学 理科 list = rootElement.elements("Book"); for (Element e : list) { System.out.println("id-" + e.attributeValue("id").toString()); System.out.println("Name-" + e.element("Name").getTextTrim()); System.out.println("Type-" + e.element("Type").getTextTrim()); System.out.println("path-" + e.element("Type").getPath()); } // 2、修改XML节点 System.out.println("修改XML节点"); for (Element e : list) { e.element("Type").setText(e.element("Type").getTextTrim()+"1"); } System.out.println("输出XML字符串"); System.out.println( doc.asXML()); // 3、保存XML String path = System.getProperty("user.dir") + "\\" + "\\xml\\Doc"+java.util.UUID.randomUUID().toString() +".xml"; Writer write=new FileWriter(path); write.write(doc.asXML()); write.flush(); write.close(); System.out.println("生成XML文件路径:"+path); } catch (Exception e) { e.printStackTrace(); } } }
输出:
F:\Java2014Code\XMLDocument\\xml\Doc.xml
getNamespace:org.dom4j.Namespace@babe [Namespace: prefix mapped to URI ""]节点名称-getName:ShopgetText:1
语文文科2数学理科3英语文科StringToXML-字符串转换成XML对象id-1Name-语文Type-文科path-/Shop/Book/Typeid-2Name-数学Type-理科path-/Shop/Book/Type修改XML节点输出XML字符串<?xml version="1.0" encoding="UTF-8"?><Shop><Book id="1"><Name>语文</Name><Type>文科1</Type></Book><Book id="2"><Name>数学</Name><Type>理科1</Type></Book></Shop>