Dom4j 操作 XML

springlin2011發表於2011-09-08
[color=blue]只需匯入dom4j.jar即可[/color]
[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]

相關文章