用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