DOM4J是dom4j.org出品的一个开源XML解析包。Dom4j是一个易用的、开源的库,用于XML,XPath和XSLT。它应用于Java平台,采用了Java集合框架并完全支持DOM,SAX和JAXP。
DOM4J下载jar包:http://downloads.sourceforge.net/dom4j/dom4j-1.6.1.jar
JAXEN(对XPath的支持):http://dist.codehaus.org/jaxen/distributions/jaxen-1.1.1.zip
DOM4J主要接口都在org.dom4j这个包里定义。
结构如下:
[img]http://dl2.iteye.com/upload/attachment/0097/6585/65ebb50e-27ce-369b-bab2-8eb9d46c45b8.jpg[/img]
-Node为所有的dom4j中XML节点定义了多态行为;
-Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为;
|-Element 定义XML 元素;
|-Document定义了XML文档;
-DocumentType 定义XML DOCTYPE声明;
-Entity定义 XML entity;
-Attribute定义了XML的属性;
-ProcessingInstruction 定义 XML 处理指令;
-CharacterData是一个标识借口,标识基于字符的节点。如CDATA,Comment, Text;
|- CDATA 定义了XML CDATA 区域;
|- Text 定义XML 文本节点;
|- Comment 定义了XML注释的行为;
参考:[url]http://zhangjunhd.blog.51cto.com/113473/126310/[/url]
DOM4J下载jar包:http://downloads.sourceforge.net/dom4j/dom4j-1.6.1.jar
JAXEN(对XPath的支持):http://dist.codehaus.org/jaxen/distributions/jaxen-1.1.1.zip
DOM4J主要接口都在org.dom4j这个包里定义。
结构如下:
[img]http://dl2.iteye.com/upload/attachment/0097/6585/65ebb50e-27ce-369b-bab2-8eb9d46c45b8.jpg[/img]
-Node为所有的dom4j中XML节点定义了多态行为;
-Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为;
|-Element 定义XML 元素;
|-Document定义了XML文档;
-DocumentType 定义XML DOCTYPE声明;
-Entity定义 XML entity;
-Attribute定义了XML的属性;
-ProcessingInstruction 定义 XML 处理指令;
-CharacterData是一个标识借口,标识基于字符的节点。如CDATA,Comment, Text;
|- CDATA 定义了XML CDATA 区域;
|- Text 定义XML 文本节点;
|- Comment 定义了XML注释的行为;
<?xml version="1.0" encoding="UTF-8"?>
<book id='history' value="cn.txt.History">
<address id='22'>100010</address>
<title id='33'>java tools</title>
<file id='44'>c:\file\</file>
</book>
package test.Dom4j;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.Element;
import org.dom4j.Attribute;
import org.dom4j.util.XMLErrorHandler;
/**
* @projectName:Test
* @packageName: test.Dom4j
* @ClassName : Dom4jTest
* @createBy :Text
* @createDate :2014-5-30 下午04:13:04
* @version :
*
*/
public class Dom4jTest {
// 读取文件转换成Document对象
public Document parseFile2Document(String filename) throws DocumentException {
//SAXReader用于读取文件
SAXReader reader = new SAXReader();
Document document = reader.read(filename);
return document;
}
@SuppressWarnings("all")
public void parseContent(Document document){
Element root = document.getRootElement();
// 打印root结点的名称
System.out.println("Root Element:" + root.getName());
// 打印root结点中属性的名字
for (Iterator i = root.attributeIterator(); i.hasNext();) {
Attribute attribute = (Attribute) i.next();
System.out
.println(attribute.getName() + ":" + attribute.getValue());
}
// 打印根元素的所有子元素的名称和值
for (Iterator i = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
System.out.println(element.getName() + ":" + element.getText());
if (element.getName().equals("address")) {
element.setText("西安市长安区"); // 修改元素的Text
}
//枚举属性
for (Iterator ia = element.attributeIterator(); ia.hasNext();) {
Attribute attribute = (Attribute) ia.next();
System.out.println(attribute.getName() + ":"
+ attribute.getData());
}
}
// 修改后进行打印
for (Iterator i = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
System.out.println(element.getName() + ":" + element.getText());
}
// 把修改后的文件保存下来
OutputFormat format = null;
XMLWriter xmlwriter = null;
// 进行格式化
format = OutputFormat.createPrettyPrint();
// 设定编码
format.setEncoding("UTF-8");
try {
xmlwriter = new XMLWriter(new FileOutputStream("test.xml"), format);
xmlwriter.write(document);
xmlwriter.flush();
xmlwriter.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 通过xsd校验xml
public void validateXMLByXSD() {
String xmlName = "src\\用户基本信息.xml";
String xsdName = "src\\用户基本信息.xsd";
try {
// 创建默认的xml错误处理器
XMLErrorHandler errorHandler = new XMLErrorHandler();
// 获取基于SAX的解析器的实例
SAXParserFactory factory = SAXParserFactory.newInstance();
// 解析器在解析时验证xml内容
factory.setValidating(true);
// 使用当前配置的工厂参数创建SAXParser的一个新实例
SAXParser parser = factory.newSAXParser();
// 创建一个读取工具
SAXReader xmlReader = new SAXReader();
// 获取要校验xml文档实例
Document xmlDocument = xmlReader.read(new File(xmlName));
// 设置 XMLReader 的基础实现中的特定属性
parser.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
parser.setProperty(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
"file:" + xsdName);
// 创建一个SAXValidator校验工具,并设置校验器的属性
SAXValidator validator = new SAXValidator(parser.getXMLReader());
// 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息
validator.setErrorHandler(errorHandler);
// 校验
validator.validate(xmlDocument);
XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
// 如果错误信息不为空,说明校验失败,打印错误信息
if (errorHandler.getErrors().hasContent()) {
System.out.println("XML文件通过XSD文件校验失败!");
writer.write(errorHandler.getErrors());
} else {
System.out.println("XML文件通过XSD文件校验成功!");
}
} catch (Exception e) {
System.out.println("xml文件" + xmlName + "通过xsd文件:" + xsdName
+ "校验失败!原因是:" + e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) throws DocumentException,
IOException {
Dom4jTest read = new Dom4jTest();
Document document = read.parseFile2Document("book.xml");
read.parseContent(document);
}
}
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
/**
* @author:LWX
* @TODO:XML操作工具类
*/
public class XmlUtil {
/**
* @author:LWX
* @TODO:字符串转换成XML对象
*/
public static Document getXMLFromString(String xmlStr) throws Exception {
Document document = DocumentHelper.parseText(xmlStr);
return document;
}
/**
* @author:LWX
* @TODO:XML对象转换成字符串
*/
public static String getStringFromXML(Document document) {
return document.asXML();
}
/**
* @author:LWX
* @TODO:读取文件转换成Document对象
*/
public static Document getDocumentFromFile(String filename)
throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(filename);
return document;
}
/**
* @author:LWX
* @TODO:获取根节点
*/
public static Element getRootElement(Document document) {
return document == null ? null : document.getRootElement();
}
/**
* @author:LWX
* @TODO:根据节点名获得子节点对象
*/
public static Element getChildElementByName(Element parentElement,
String elementName) {
return parentElement == null ? null : parentElement
.element(elementName);
}
/**
* @author:LWX
* @TODO:获得节点的值
*/
public static String getElementText(Element element) {
return element == null ? null : element.getText();
}
/**
* @author:LWX
* @TODO:获得某个节点的属性值
*/
public static String getAttributeValue(Element element, String attributeName) {
return element == null ? null : element.attribute(attributeName)
.getValue();
}
/**
* @author:LWX
* @TODO:添加一个节点
*/
public static Element addElement(Element parentElement, String elementName,
Map<String, String> attributeMap) {
if (parentElement == null) {
return null;
}
Element newElement = parentElement.addElement(elementName);
for (String key : attributeMap.keySet()) {
newElement.addAttribute(key, attributeMap.get(key));
}
return parentElement;
}
/**
* @author:LWX
* @TODO:删除对应节点
*/
@SuppressWarnings("all")
public static void removeElement(Element parentElement,
String attributeName, String attributeValue) {
Element resultElement = null;
if (parentElement != null) {
for (Iterator i = parentElement.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
if (attributeValue != null
&& attributeValue.equals(element
.attributeValue(attributeName))) {
resultElement = element;
break;
}
}
parentElement.remove(resultElement);
}
}
/**
* @author:LWX
* @TODO:更新属性信息
*/
@SuppressWarnings("all")
public static void updateElement(Element element, String attributeName,
String attributeValue) {
if (element != null) {
element.attribute(attributeName).setValue(attributeValue);
}
}
/**
* @author:LWX
* @TODO:通过属性值定位Node获得节点对象 节点和参数格式 /report/columns,
* column[@colCode='DEPTNAME']
*/
@SuppressWarnings("all")
public static Element getElementByNode(Document document, String nodeName,
String attributeName) {
Element element = null;
Node root = document.selectSingleNode(nodeName);
List list = root.selectNodes(attributeName);
for (Object obj : list) {
element = (Element) obj;
break;
}
return element;
}
/**
* @author:LWX
* @TODO:根据属性名的值进行升序或降序 nodeName格式 /report/columns attributeName格式@order
*
*/
@SuppressWarnings("all")
public static List<Element> getElementsByOrder(Document document,
String nodeName, String attributeName, boolean isIncr) {
List<Element> nodes = document.selectNodes(nodeName, attributeName);
if (!isIncr) {
Collections.reverse(nodes);
}
return nodes;
}
/**
* @author:LWX
* @TODO:通过节点名获得节点对象
*/
@SuppressWarnings("all")
public static Element getElementByNodeName(Document document,
String nodeName) {
List<Element> nodes = document.selectNodes(nodeName);
return nodes == null && nodes.size() <= 0 ? null : nodes.get(0);
}
public static void main(String[] args) throws Exception, IOException {
Document document = XmlUtil.getDocumentFromFile("test.xml");
Element rootElement = XmlUtil.getRootElement(document);
System.out.println(XmlUtil.getElementText(XmlUtil
.getChildElementByName(rootElement, "querySql")));
Element colElement = XmlUtil.getChildElementByName(rootElement,
"columns");
System.out.println(XmlUtil.getElementByNode(document,
"/report/columns", "column[@colCode='DEPTNAME']")
.attributeValue("colName"));
XmlUtil.removeElement(colElement, "colCode", "DEPTNAME");
Map<String, String> map = new HashMap<String, String>();
map.put("colCode", "COUNT");
map.put("colName", "总数");
map.put("colType", "int");
map.put("isVisible", "true");
map.put("order", "4");
XmlUtil.addElement(colElement, "column", map);
XmlUtil.updateElement(XmlUtil.getElementByNode(document,
"/report/columns", "column[@colCode='DEPTID']"), "isVisible",
"false");
List<Element> nodes = XmlUtil.getElementsByOrder(document,
"/report/columns/column", "@order", false);
for (Element e : nodes) {
System.out.println("colCode : " + e.attributeValue("colCode"));
System.out.println("colName : " + e.attributeValue("colName"));
}
System.out.println(XmlUtil.getElementByNodeName(document,
"/report/querySql").getName());
System.out.println(XmlUtil.getStringFromXML(document));
String initStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
initStr += "<report measureCode=\"mms_user_dept\" measureName=\"部门用户统计\"></report>";
document = XmlUtil.getXMLFromString(initStr);
XmlUtil.addElement(XmlUtil.getRootElement(document), "columns", map);
System.out.println(XmlUtil.getStringFromXML(document));
}
}
参考:[url]http://zhangjunhd.blog.51cto.com/113473/126310/[/url]