?? xmlprocessutil.java
字號:
package test;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* XML 處理工具
*
* @author zlh
*
*/
public class XmlProcessUtil {
private Document document = null;
/**
* 建立一個XML文檔
*
* @return Document
*/
public Document createXMLDocument() {
/** 建立document對象 */
document = DocumentHelper.createDocument();
/** 建立XML文檔的根rootName */
Element booksElement = document.addElement("books");
/** 加入一行注釋 */
booksElement.addComment("This is a test for dom4j, 測試.");
// 加入第一個book節(jié)點(diǎn)
Element bookElement = booksElement.addElement("book");
// 加入show屬性內(nèi)容
bookElement.addAttribute("show", "yes");
// 加入title節(jié)點(diǎn)
Element titleElement = bookElement.addElement("title");
// 為title設(shè)置內(nèi)容
titleElement.setText("Dom4j 測試");
// 類似的完成后兩個book
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show", "yes");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene Studing");
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show", "no");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene in Action");
// 加入owner節(jié)點(diǎn)
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
return document;
}
/**
* * 打開文檔 *
*
* @param filePath
* 文檔路徑
*/
public Document openXML(String filePath) {
try {
SAXReader saxReader = new SAXReader();
this.document = saxReader.read(filePath);
System.out.println("openXML(String filePath) successful ...");
} catch (Exception e) {
System.out.println("openXML() Exception:" + e.getMessage());
}
return this.document;
}
/**
* * 添加根節(jié)點(diǎn)的child *
*
* @param nodeName
* 節(jié)點(diǎn)名 *
* @param nodeValue
* 節(jié)點(diǎn)值
*/
public void addNodeFromRoot(String nodeName, String nodeValue) {
Element root = this.document.getRootElement();
Element level1 = root.addElement(nodeName);
level1.addText(nodeValue);
}
/**
* * 獲得某個節(jié)點(diǎn)的值 *
*
* @param nodeName
* 節(jié)點(diǎn)名稱
*/
public String getElementValue(String nodeName) {
try {
Node node = document.selectSingleNode("//" + nodeName);
return node.getText();
} catch (Exception e1) {
System.out
.println("getElementValue() Exception:" + e1.getMessage());
return null;
}
}
/**
* * 獲得某個節(jié)點(diǎn)的子節(jié)點(diǎn)的值 *
*
* @param nodeName *
* @param childNodeName *
* @return
*/
public String getElementValue(String nodeName, String childNodeName) {
try {
Node node = this.document.selectSingleNode("//" + nodeName + "/"
+ childNodeName);
return node.getText();
} catch (Exception e1) {
System.out
.println("getElementValue() Exception:" + e1.getMessage());
return null;
}
}
/**
* * 設(shè)置一個節(jié)點(diǎn)的text *
*
* @param nodeName
* 節(jié)點(diǎn)名 *
* @param nodeValue
* 節(jié)點(diǎn)值
*/
public void setElementValue(String nodeName, String nodeValue) {
try {
Node node = this.document.selectSingleNode("//" + nodeName);
node.setText(nodeValue);
} catch (Exception e1) {
System.out
.println("setElementValue() Exception:" + e1.getMessage());
}
}
/**
* * 設(shè)置一個節(jié)點(diǎn)值 *
*
* @param nodeName
* 父節(jié)點(diǎn)名 *
* @param childNodeName
* 節(jié)點(diǎn)名 *
* @param nodeValue
* 節(jié)點(diǎn)值
*/
public void setElementValue(String nodeName, String childNodeName,
String nodeValue) {
try {
Node node = this.document.selectSingleNode("//" + nodeName + "/"
+ childNodeName);
node.setText(nodeValue);
} catch (Exception e1) {
System.out
.println("setElementValue() Exception:" + e1.getMessage());
}
}
/**
*
* @param filename
* @param document
* @return 成功返回 0, 失敗返回 -1
*/
public int saveXMLFile(String filename, Document document,
String xmlFileEncode) {
int returnValue = -1;
XMLWriter writer = null;
String encode = xmlFileEncode;
if (null == xmlFileEncode || "".equals(xmlFileEncode))
encode = "GBK";
try {
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML編碼 */
if ("GBK".equals(encode)) {
format.setEncoding("GBK");
writer = new XMLWriter(new FileWriter(filename), format);
} else {
// 如果是UTF-8 FileWriter 改用 FileOutputStream,否則在讀取此XML時報(bào)錯!
format.setEncoding("UTF-8");
writer = new XMLWriter(new FileOutputStream(filename), format);
}
writer.write(document);
writer.close();
returnValue = 0;
} catch (Exception ex) {
ex.printStackTrace();
}
return returnValue;
}
/**
* @param args
*/
public static void main(String[] args) {
XmlProcessUtil x = new XmlProcessUtil();
Document doc = x.createXMLDocument();
x.saveXMLFile("c:\\test1.xml", doc, "GBK");
doc = x.openXML("c:\\test1.xml");
//System.out.println(x.getElementValue("owner",""));
System.out.println(x.getElementValue("owner"));
System.out.println(doc.selectSingleNode("//books/owner").getText());
//System.out.println(doc.selectSingleNode("//books/book1/title1").getText());
//下面測試遍歷及修改
/** 修改內(nèi)容之一: 如果book節(jié)點(diǎn)中show屬性的內(nèi)容為yes,則修改成no */
/** 先用xpath查找對象 */
List list = doc.selectNodes("/books/book/@show" );
Iterator iter = list.iterator();
while(iter.hasNext()){
Attribute attribute = (Attribute)iter.next();
System.out.println("attribute.getValue():"+attribute.getValue());
if(attribute.getValue().equals("yes")){
attribute.setValue("no");
}
}
/**
* 修改內(nèi)容之二: 把owner項(xiàng)內(nèi)容改為test-modify.
* 并在owner節(jié)點(diǎn)中加入date節(jié)點(diǎn),date節(jié)點(diǎn)的內(nèi)容為2008-03-31,還為date節(jié)點(diǎn)添加一個屬性type
*/
list = doc.selectNodes("/books/owner" );
iter = list.iterator();
if(iter.hasNext()){
Element ownerElement = (Element)iter.next();
ownerElement.setText("test-modify.");
Element dateElement = ownerElement.addElement("date");
dateElement.setText("2008-03-31");
dateElement.addAttribute("type","Gregorian calendar");
}
/** 修改內(nèi)容之三: 若title內(nèi)容為book1'll remove.,則刪除該節(jié)點(diǎn) */
list = doc.selectNodes("/books/book");
iter = list.iterator();
while(iter.hasNext()){
Element bookElement = (Element)iter.next();
Iterator iterator = bookElement.elementIterator("title");
while(iterator.hasNext()){
Element titleElement=(Element)iterator.next();
if(titleElement.getText().equals("book1'll remove.")){
bookElement.remove(titleElement);
}
}
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -