Dom4j 操作 XML
[color=blue]只需匯入dom4j.jar即可[/color]
[color=blue]Dom4j解析XML[/color]
[color=blue]Dom4j生成XML[/color]
[code]
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class CreateXML {
public static void main(String[] args) {
CreateXML c = new CreateXML();
Document document = c.createDocument();
c.writeXML(document, "d:/message.xml");
}
/**
* 寫入檔案
*/
private void writeXML(Document doc, String path){
try {
XMLWriter writer = new XMLWriter(new FileOutputStream(new File(path)));
writer.write(doc);
writer.close();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
//輸出到控制檯
writer = new XMLWriter(System.out, format);
writer.write(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 建立Document XML檔案
**/
private Document createDocument() {
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement(QName.get("Message", "http://www.baidu.com"));
Element catalogElement = rootElement.addElement("Header");
catalogElement.addElement("Version").addText("1.0");
catalogElement.addElement("MessageId").addText("STO");
catalogElement.addElement("CorrelationId").addText("10000");
catalogElement.addElement("FromSite").addText("AIRPORT_SITE");
catalogElement.addElement("ToService").addText("RegisterService");
catalogElement.addElement("Personnel").addText("0001223");
catalogElement.addElement("Reserve").addText("STRING");
catalogElement.addElement("GroupId").addText("1000001");
catalogElement.addElement("GroupSize").addText("3");
catalogElement.addElement("GroupIndex").addAttribute("name", "abc")
.addElement("GroupIndex2").addText("2");
Element articleElement = catalogElement.addElement("ToSites");
articleElement.addElement("ToSite").addText("DATA_CENTER_SITE");
return document;
}
}
[/code]
[color=blue]Dom4j解析XML[/color]
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Dom4jReardXML {
public static void main(String args[]) {
testParseXMLData("D:/MyWorkspace/mytest/person.xml");
}
/**
* @param xmlFilePath xml檔案路徑
* @return Document物件
*/
public static Document parse2Document(String xmlFilePath){
SAXReader reader = new SAXReader();
Document document = null;
File f = null;
try {
f = new File(xmlFilePath);
InputStream in = new FileInputStream(f);
document = reader.read(in);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("讀取檔案發生異常,請檢查CLASSPATH和檔名是否存在!");
e.printStackTrace();
}
return document;
}
public static void testParseXMLData(String xmlFileName) {
Document document = null;
document = parse2Document(xmlFileName);
//獲取文件的根元素
Element root = document.getRootElement();
StringBuffer sb = new StringBuffer();
sb.append("通過Dom4j解析XML,並輸出資料:\n");
sb.append(xmlFileName + "\n");
sb.append("----------------遍歷start----------------\n");
//遍歷當前元素(根元素)的子元素
for (Iterator i_pe = root.elementIterator(); i_pe.hasNext();) {
Element e_pe = (Element) i_pe.next();
//獲取當前元素的名字
String person = e_pe.getName();
//獲取當前元素的屬性
String id = e_pe.attributeValue("id");
String sex = e_pe.attributeValue("sex");
String name = e_pe.element("name").getText();
String age = e_pe.element("age").getText();
//將資料存放到緩衝區字串物件中
sb.append(person + ":\n");
sb.append("\tid=" + id + " sex=" + sex + "\n");
sb.append("\t" + "name=" + name + " age=" + age + "\n");
//獲取當前元素e_pe下的子元素adds
Element e_adds = e_pe.element("adds");
sb.append("\t" + e_adds.getName() + "\n");
//遍歷當前元素e_adds(在此是adds元素)的子元素
for (Iterator i_adds = e_adds.elementIterator(); i_adds.hasNext();) {
Element e_add = (Element) i_adds.next();
String code = e_add.attributeValue("code");
String add = e_add.getTextTrim();
sb.append("\t\t" + e_add.getName() + ":" + " code=" + code + " value=\"" + add + "\"\n");
}
sb.append("\n");
}
sb.append("-----------------遍歷end-----------------\n");
System.out.println(sb.toString());
//選擇性節點,遍歷
System.out.println("---------通過XPath獲取一個元素----------");
Node node1 = document.selectSingleNode("/doc/person");
System.out.println("輸出節點:" +
"\t"+node1.asXML());
Node node2 = document.selectSingleNode("/doc/person/@sex");
System.out.println("輸出節點:" +
"\t"+node2.asXML());
Node node3 = document.selectSingleNode("/doc/person[name=\"zhangsan\"]/age");
System.out.println("輸出節點:" +
"\t"+node3.asXML());
System.out.println("\n---------XPath獲取List節點測試------------");
List list = document.selectNodes("/doc/person[name=\"zhangsan\"]/adds/add");
for(Iterator it=list.iterator();it.hasNext();){
Node nodex=(Node)it.next();
System.out.println(nodex.asXML());
}
System.out.println("\n---------通過ID獲取元素的測試----------");
System.out.println("陷阱:通過ID獲取,元素ID屬性名必須為“大寫ID”,小寫的“id”會認為是普通屬性!");
String id22 = document.elementByID("22").asXML();
String id23 = document.elementByID("23").asXML();
String id24 = null;
if (document.elementByID("24") != null) {
id24 = document.elementByID("24").asXML();
} else {
id24 = "null";
}
System.out.println("id22= " + id22);
System.out.println("id23= " + id23);
System.out.println("id24= " + id24);
}
}
[color=blue]Dom4j生成XML[/color]
[code]
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class CreateXML {
public static void main(String[] args) {
CreateXML c = new CreateXML();
Document document = c.createDocument();
c.writeXML(document, "d:/message.xml");
}
/**
* 寫入檔案
*/
private void writeXML(Document doc, String path){
try {
XMLWriter writer = new XMLWriter(new FileOutputStream(new File(path)));
writer.write(doc);
writer.close();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
//輸出到控制檯
writer = new XMLWriter(System.out, format);
writer.write(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 建立Document XML檔案
**/
private Document createDocument() {
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement(QName.get("Message", "http://www.baidu.com"));
Element catalogElement = rootElement.addElement("Header");
catalogElement.addElement("Version").addText("1.0");
catalogElement.addElement("MessageId").addText("STO");
catalogElement.addElement("CorrelationId").addText("10000");
catalogElement.addElement("FromSite").addText("AIRPORT_SITE");
catalogElement.addElement("ToService").addText("RegisterService");
catalogElement.addElement("Personnel").addText("0001223");
catalogElement.addElement("Reserve").addText("STRING");
catalogElement.addElement("GroupId").addText("1000001");
catalogElement.addElement("GroupSize").addText("3");
catalogElement.addElement("GroupIndex").addAttribute("name", "abc")
.addElement("GroupIndex2").addText("2");
Element articleElement = catalogElement.addElement("ToSites");
articleElement.addElement("ToSite").addText("DATA_CENTER_SITE");
return document;
}
}
[/code]
相關文章
- XML和Dom4jXML
- dom4j遍歷巢狀xml巢狀XML
- java的XML解析(DOM4J技術)JavaXML
- DOM4J 解析 XML 之忽略轉義字元XML字元
- 【超好用API推薦】用dom4j建立XML檔案並寫入節點APIXML
- C# 操作xml(轉)C#XML
- PHP操作xml詳解PHPXML
- PHP xml 轉陣列 陣列轉 xml 操作PHPXML陣列
- xml操作的幾種方法XML
- PHP透過DOM操作XMLPHPXML
- mybatis mapper.xml批次刪除操作MyBatisAPPXML
- QT: 操作主從檢視及XMLQTXML
- Spring中基於XML方式的AOP操作SpringXML
- XML基本操作-建立(DOM和LOINQ)和LINQ查詢和儲存XML
- 使用jaxp解析器dom方式對xml節點進行操作XML
- C#XmlHelper幫助類操作Xml文件的通用方法彙總C#XML
- XMLXML
- dom4j 根據xml節點路徑查詢節點,找到對應的目標節點下的子節點,對節點Text值進行修改XML
- 使用FOR XML AUTO控制XML輸出KHXML
- XML文件XML
- Xml解析XML
- 序列化篇 生成xml 以及讀取xmlXML
- XML基礎XML
- php建立XMLPHPXML
- Java解析XMLJavaXML
- setting.xmlXML
- go 解析xmlGoXML
- 7.86 EXTRACT (XML)XML
- xml筆記XML筆記
- xml檔案XML
- L.xmlXML
- iOS – XML解析iOSXML
- XML介紹XML
- XML 元素概述XML
- 淺析XMLXML
- XML與JSONXMLJSON
- WebService XML SoapFormatterWebXMLORM
- Mybatis去xml化:我再也不想寫xml了MyBatisXML
- Python xml.etree.ElementTree讀寫xml檔案例項PythonXML