用Dom4j增刪改XML文件
本示例代碼引用了以下兩個包:
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
下載與安裝
dom4j是sourceforge.net上的一個開源項目,主要用于對XML的解析。dom4j專門針對Java開發,使用起來非常簡單、直觀。
可以到http://sourceforge.net/projects/dom4j下載其最新版。
dom4j1.6解壓后有一個dom4j-1.6.1.jar文件,這就是應用時需要引入的類包,另外還有一個jaxen-1.1-beta-6.jar
文件,需要引入,否則執行時可能拋java.lang.NoClassDefFoundError:
org/jaxen/JaxenException異常
代碼如下:
package com.tl.common.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* @author zhangql
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates. To enable and disable the creation of type
* comments go to Window>Preferences>Java>Code Generation.
*/
public final class ConfigtUtil
{
/**
* 空方法,未實現
*/
public void getRootNodeAttribute()
{
//TODO
}
/** 返回節點路徑
* @param rootNodeName
* @param childNodeName
* @return String
*/
public String getNodePath(String rootNodeName,String childNodeName)
{
String result = null;
if(rootNodeName== "" || rootNodeName == null ||
childNodeName == "" || childNodeName == null)
{
return result;
}
result = getNodePath(rootNodeName,childNodeName,null);
return result;
}
/**
* 返回節點路徑
* @param rootNodeName
* @param childNodeName
* @param childAttributeName
* @return String
*/
public String getNodePath(String rootNodeName,String childNodeName,String childAttributeName)
{
String result = null;
if(rootNodeName== "" || rootNodeName == null ||
childNodeName == "" || childNodeName == null )
{
return result;
}
String dima = "/";
StringBuffer nodePath = new StringBuffer();
nodePath.append(rootNodeName);
nodePath.append(dima).append(childNodeName);
if(childAttributeName != null && childAttributeName != "")
{
nodePath.append(dima).append("@");
nodePath.append(childAttributeName);
}
result = nodePath.toString();
return result;
}
/**
* 更新子節點屬性值
* @param filePathAndName
* @param rootNodeName
* @param childNodeName
* @param childAttributeName
* @param childAttributeValue
* @return boolean
* @throws DocumentException
* @throws IOException
*/
public boolean updateChildNodeAttributeValue(String filePathAndName, String rootNodeName,
String childNodeName,String childAttributeName,
String childAttributeValue) throws DocumentException, IOException
{
boolean result = false;
if(filePathAndName == "" || filePathAndName == null ||
rootNodeName== "" || rootNodeName == null ||
childNodeName == "" || childNodeName == null ||
childAttributeName == "" || childAttributeName == null ||
childAttributeValue == "" || childAttributeValue == null)
{
return result;
}
String nodePath = getNodePath(rootNodeName,childNodeName,childAttributeName);
Document document = getDocument(filePathAndName);
List list = getListByDocument(document,nodePath);
for(Iterator iter = list.iterator();iter.hasNext();)
{
Attribute attribute = (Attribute) iter.next();
attribute.setValue(childAttributeValue);
}
result = writerConfigFileByFormat(filePathAndName,document);
return result;
}
/**
* 取得Document中指定節點下的所有節點集合
* @param document
* @param nodeName
* @return List
*/
public List getListByDocument(Document document,String nodeName)
{
if(document == null || nodeName == null || nodeName == "")
{
return null;
}
List list = null;
list = document.selectNodes(nodeName);
return list;
}
/**
* 獲取Document
* @param filePathAndName
* @return Document
* @throws DocumentException
*/
public Document getDocument(String filePathAndName)
throws DocumentException
{
Document document = null;
if (filePathAndName == null || filePathAndName == "")
{
return document;
}
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File(filePathAndName));
return document;
}
/**
* 獲取根節點下的子節點集合
* @param filePathAndName
* @param rootNodeName
* @param childNodeName
* @return List
* @throws DocumentException
*/
public List getRootListByChildNode(String filePathAndName, String rootNodeName,
String childNodeName) throws DocumentException
{
List result = null;
if (filePathAndName == null || filePathAndName == "" ||
rootNodeName == null || rootNodeName == "" ||
childNodeName == null || childNodeName =="")
{
return result;
}
String nodePath = getNodePath(rootNodeName,childNodeName);
result = getRootNodeList(filePathAndName,nodePath);
return result;
}
/**
* 獲取根節點集合
* @param filePathAndName
* @param rootNodeName
* @return List
* @throws DocumentException
*/
public List getRootNodeList(String filePathAndName, String rootNodeName)
throws DocumentException
{
List list = null;
if (filePathAndName == null || filePathAndName == "" ||
rootNodeName == null || rootNodeName == "")
{
return list;
}
list = getNodeList(filePathAndName,rootNodeName);
return list;
}
/**
* 取得節點集合
* @param filePathAndName
* @param nodePath
* @return List
* @throws DocumentException
*/
public List getNodeList(String filePathAndName, String nodePath) throws DocumentException
{
List list = null;
if (filePathAndName == null || filePathAndName == "" ||
nodePath == null || nodePath == "")
{
return list;
}
list = getListByDocument(getDocument(filePathAndName),nodePath);
return list;
}
/**
* 獲取節點的值
* @param filePathAndName
* @param rootNodeName
* @param nodeName
* @return String
* @throws DocumentException
*/
public String getNodeValue(String filePathAndName, String rootNodeName,
String nodeName) throws DocumentException
{
String result = null;
if (filePathAndName == null || filePathAndName == ""
|| rootNodeName == null || rootNodeName == ""
|| nodeName == null || nodeName == "")
{
return result;
}
List list = getRootNodeList(filePathAndName, rootNodeName);
result = getNodeValue(list, nodeName);
return result;
}
/**
* 獲取子節點值
* @param list
* @param childNodeName
* @return String
*/
public String getChildNodeValue(List list,String childNodeName)
{
String result = null;
if(list.isEmpty() || childNodeName == "" || childNodeName == null)
{
return result;
}
result = getNodeValue(list,childNodeName);
return result;
}
/**
* 獲取子節點值
* @param list
* @return String
*/
public String getChildNodeValue(List list)
{
String result = null;
if(list.isEmpty())
{
return result;
}
for(Iterator iter = list.iterator();iter.hasNext();)
{
Element element = (Element)iter.next();
result = element.getText();
}
return result;
}
/**
* 取得子節點的屬性值
* @param filePathAndName
* @param rootNodeName
* @param childNodeName
* @param childAttributeName
* @return String
* @throws DocumentException
*/
public String getChildNodeAttributeValue(String filePathAndName,
String rootNodeName, String childNodeName, String childAttributeName)
throws DocumentException
{
String result = null;
if(filePathAndName == "" || filePathAndName == null ||
rootNodeName == "" || rootNodeName == null ||
childNodeName == "" || childNodeName == null ||
childAttributeName == null || childAttributeName == "")
{
return result;
}
String nodePath = getNodePath(rootNodeName, childNodeName,childAttributeName);
List list = getNodeList(filePathAndName, nodePath);
result = getChildNodeAttributeValue(list);
return result;
}
/**
* 此方法未實現
* @param list
* @param nodeName
* @param attributeName
* @return
*/
public String getChildNodeAttributeValue(List list,String nodeName,String attributeName)
{
String result = null;
if(list.isEmpty() || nodeName == null || nodeName =="" ||
attributeName == null || attributeName =="")
{
return result;
}
//TODO
// String nodePath = getNodePath(nodeName,attributeName);
//
// for (Iterator iter = list.iterator(); iter.hasNext();)
// {
// Element element = (Element) iter.next();
// System.out.println("---->"+element.selectNodes(nodeName).size());
// System.out.println("---->"+element.selectNodes(nodePath).size());
// for(Iterator elementIter = element.selectNodes(nodeName).iterator();elementIter.hasNext();)
// {
// Attribute attribute = (Attribute)elementIter.next();
// System.out.println("---->"+attribute.getValue());
// }
//// result = getChildNodeAttributeValue(element.selectNodes(nodeName));
// }
return result;
}
/**
* 獲取子節點屬性的值
* @param list
* @param childNodeAttributeName
* @return String
*/
public String getChildNodeAttributeValue(List list,String childNodeAttributeName)
{
String result = null;
if(list.isEmpty() || childNodeAttributeName == null || childNodeAttributeName =="")
{
return result;
}
result = getNodeValue(list,childNodeAttributeName);
return result;
}
/**
* 獲取子節點屬性的值
* @param list
* @return String
*/
public String getChildNodeAttributeValue(List list)
{
String result = null;
if(list.isEmpty())
{
return result;
}
for(Iterator iter = list.iterator();iter.hasNext();)
{
Attribute attribute = (Attribute)iter.next();
result = attribute.getValue();
}
return result;
}
/**
* 獲取節點值
* @param nodeList
* @param nodeName
* @return String
*/
public String getNodeValue(List nodeList, String nodeName)
{
String result = null;
if (nodeList.isEmpty())
{
return result;
}
for (Iterator iter = nodeList.iterator(); iter.hasNext();)
{
Element element = (Element) iter.next();
for (Iterator it = element.selectNodes(nodeName).iterator(); it.hasNext();)
{
result = ((Element) it.next()).getText();
}
}
return result;
}
/**
* 更新節點值
* @param filePathAndName
* @param rootNodeName
* @param nodeName
* @param NodeVlaue
* @return boolean
* @throws Exception
*/
public boolean updateNodeValue(String filePathAndName, String rootNodeName,
String nodeName, String NodeVlaue) throws Exception
{
boolean result = false;
Document document = getDocument(filePathAndName);
List list = document.selectNodes(rootNodeName);
for (Iterator iter = list.iterator(); iter.hasNext();)
{
Element element = (Element) iter.next();
for (Iterator childIterator = element.selectNodes(nodeName)
.iterator(); childIterator.hasNext();)
{
Element childElement = (Element) childIterator.next();
childElement.setText(NodeVlaue);
}
}
/** 將document中的內容寫入文件中 */
result = writerConfigFileByFormat(filePathAndName,document);
return result;
}
/**
* 創建XMLWriter
* @param filePathAndName
* @return XMLWriter
* @throws IOException
*/
private XMLWriter createXMLWriter(String filePathAndName) throws IOException
{
XMLWriter writer = null;
writer = new XMLWriter(new FileWriter(new File(filePathAndName)));
return writer;
}
/**
* 創建XMLWriter
* @param filePathAndName
* @param outputFormat
* @return XMLWriter
* @throws IOException
*/
private XMLWriter createXMLWriter(String filePathAndName,OutputFormat outputFormat) throws IOException
{
XMLWriter writer = null;
writer = new XMLWriter(new FileWriter(new File(filePathAndName)), outputFormat);
return writer;
}
/**
* 以GBK格式化寫文件
* @param filePathAndName
* @param document
* @return boolean
*/
public boolean writerConfigFileByFormat(String filePathAndName,Document document)
{
boolean result = false;
try
{
result = writerConfigFileByFormat(filePathAndName,document,"GBK");
}
catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
/**
* 格式化寫文件
* @param filePathAndName
* @param document
* @param encoding
* @return boolean
*/
public boolean writerConfigFileByFormat(String filePathAndName,Document document,String encoding)
{
boolean result = false;
try
{
XMLWriter writer = null;
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
writer = createXMLWriter(filePathAndName, format);
writerConfigFile(writer,document);
result = true;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
/**
* 寫文件
* @param filePathAndName
* @param document
* @return boolean
* @throws IOException
*/
public boolean writerConfigFile(String filePathAndName,Document document) throws IOException
{
boolean result = false;
XMLWriter writer = createXMLWriter(filePathAndName);
writerConfigFile(writer,document);
result = true;
return result;
}
/**
* 寫文件
* @param xmlWriter
* @param document
* @return boolean
* @throws IOException
*/
public boolean writerConfigFile(XMLWriter xmlWriter,Document document) throws IOException
{
boolean result = false;
xmlWriter.write(document);
xmlWriter.close();
result = true;
return result;
}
/**
* 此方法為網上轉載,臨時加入到本類,未作代碼驗證
* 建立一個XML文檔,文檔名由輸入屬性決定
* @param filename 需建立的文件名
* @return 返回操作結果, 0表失敗, 1表成功
*/
public int createXMLFile(String filename)
{
/** 返回操作結果, 0表失敗, 1表成功 */
int returnValue = 0;
/** 建立document對象 */
Document document = DocumentHelper.createDocument();
/** 建立XML文檔的根books */
Element booksElement = document.addElement("books");
/** 加入一行注釋 */
booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
/** 加入第一個book節點 */
Element bookElement = booksElement.addElement("book");
/** 加入show屬性內容 */
bookElement.addAttribute("show","yes");
/** 加入title節點 */
Element titleElement = bookElement.addElement("title");
/** 為title設置內容 */
titleElement.setText("Dom4j Tutorials");
/** 類似的完成后兩個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節點 */
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
try
{
/** 將document中的內容寫入文件中 */
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
/** 執行成功,需返回1 */
returnValue = 1;
}
catch(Exception ex)
{
ex.printStackTrace();
}
return returnValue;
}
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=959095