Demo:
package com.dom4j.red;
import java.io.File;
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.Node;
import org.dom4j.Text;
import org.dom4j.io.SAXReader;
/**
* 完整的读取xml的内容
* @author zhiyong
*
*/
public class Demo3 {
//定义变量存放
public static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws DocumentException {
//创建xml解析器对象
SAXReader reader = new SAXReader();
//读取xml文档,返回Document对象
Document document = reader.read(new File("./src/contact.xml"));
//读取根标签下的所有子标签
Element rootEle = document.getRootElement();
String str = getChildNodes(rootEle);
System.out.println(str);
}
/**
* 获取当前标签下的所有子标签
* @param ele
*/
public static String getChildNodes(Element ele){
//开始标签
sb.append("<" + ele.getName());
//获取属性
List<Attribute> attList = ele.attributes();
for(Attribute att : attList){
String attName = att.getName();
String attValue = att.getValue();
sb.append(" " + attName + "=\"" + attValue + "\"");
}
sb.append(">");
//获取传入标签下的直接子节点
Iterator<Node> it = ele.nodeIterator();
while(it.hasNext()){
Node node = it.next();
//标签
if(node instanceof Element){
Element n = (Element)node;
getChildNodes(n);
}
//文本
if(node instanceof Text){
Text t = (Text)node;
sb.append(t.getText());
}
}
//结束标签
sb.append("</" + ele.getName() + ">");
return sb.toString();
}
xml文件
<?xml version="1.0" encoding="utf-8"?>
<contactList>
<contact id="001" att1="属性值1">
<name>木丁西<nameNode>小刘</nameNode></name>
<age>18</age>
<phone>18071897425</phone>
<email>1012421396@qq.com</email>
<qq>1012421396</qq>
</contact>
<木丁西>
这是个什么鬼。
</木丁西>
<contact id="002">
<name>刘先森</name>
<age>20</age>
<phone>18771897466</phone>
<email>561242139@qq.com</email>
<qq>561242139</qq>
</contact>
<abc>
</abc>
</contactList>
效果: