您的位置:首页 > 编程语言

使用dom4j解析XML文件(自己的代码)

2010-07-27 13:19 796 查看
package userweb.action.buy.haoTest;

import org.dom4j.io.SAXReader;
import org.dom4j.tree.AbstractAttribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import java.util.Iterator;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: Anlei<br>
* <b>Date</b>: 2010-3-26 15:53:51<br>
* <b>Note</b>: Dom4j遍历解析XML测试
*/
public class TestReadXMLDom4jNew {

// dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,
//具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件
// 读C://s.xml文件获得文件的属性值
/**
* 获取指定xml文档的Document对象,xml文件必须在classpath中可以找到
*
* @param xmlFilePath xml文件路径
* @return Document对象
*/
public static Document parse2Document(String xmlFilePath) {
File xmlFile = new File(xmlFilePath);
SAXReader saxReader = new SAXReader();
Document document = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(xmlFile);
document = saxReader.read(fis);
} catch (DocumentException e) {
System.out.println(e.getMessage());
System.out.println("读取classpath下xmlFileName文件发生异常,请检查CLASSPATH和文件名是否存在!");
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return document;
}

/**
* 遍历xml文件获得各节点的值
* @param xmlFileName 文件名(C://person.xml)
*/
public static void testParseXMLData(String xmlFileName) {
//产生一个解析器对象
//将xml文档转换为Document的对象
Document document = parse2Document(xmlFileName);
//获取文档的根元素
Element root = document.getRootElement();
//定义个保存输出xml数据的缓冲字符串对象
StringBuffer sb = new StringBuffer();
sb.append("通过Dom4j解析XML,并输出数据:/n");
sb.append(xmlFileName + "/n");
sb.append("----------------遍历start----------------/n");
//遍历当前元素(在此是根元素)的子元素
for (Iterator i_pe = root.elementIterator(); i_pe.hasNext();) {
Element e_pe = (Element) i_pe.next();
// 获得person 元素的所有属性列表
List elementList = e_pe.attributes();
//获取当前元素的名字是:person
String person = e_pe.getName();
//获取当前元素的id和sex属性的值并分别赋给id,sex变量
// String id = e_pe.attributeValue("id");
// String sex = e_pe.attributeValue("sex");
// 将数据存放到缓冲区字符串对象中
sb.append(person + ":/n");
for (Iterator iter = elementList.iterator(); iter.hasNext();) {
//将每个属性转化为一个抽象属性,然后获取其名字和值
AbstractAttribute per = (AbstractAttribute)iter.next();
String stName = per.getName();
String stValue = per.getValue();
sb.append("/tid=" + stName + " sex=" + stValue + "/n");
// System.out.println("/tName:" +stName + ";Value:" + stValue+"/n");
//获取当前元素的id和sex属性的值并分别赋给id,sex变量
// System.out.println("id:" +stName + ";sex:" + stValue);
}
String name = e_pe.element("name").getText();
String age = e_pe.element("age").getText();

// sb.append("/tid=" + id + " sex=" + sex + "/n");
sb.append("/t" + "name=" + name + " age=" + age + "/n");
// 获取当前元素e_pe(在此是person元素)下的子元素adds
Element addsList = e_pe.element("adds");
sb.append("/t" + addsList.getName() + "/n");
//遍历当前元素adds(在此是adds元素)的子元素
// <add code="wwww">homewww add</add>
// code = www
for (Iterator iter = addsList.elementIterator(); iter.hasNext();) {
Element ele = (Element)iter.next();
String sg = ele.getTextTrim();
sb.append(sg + "/n");
//将每个属性转化为一个抽象属性
// List e = ele.attributes(); 这个方法获得ele.attributes()和ele.attributeIterator()一样的
Iterator e = ele.attributeIterator();
//方法1
while (e.hasNext()) {
AbstractAttribute aa = (AbstractAttribute)e.next();
String stName = aa.getName();
String stValue = aa.getValue();
sb.append(stName + "=" + stValue + "/n");
}
///方法2
// for (Iterator itr = e.iterator(); itr.hasNext();) {
// // 将每个属性转化为一个抽象属性,然后获取其名字和值
// AbstractAttribute aa = (AbstractAttribute)itr.next();
// String stName = aa.getName();
// String stValue = aa.getValue();
// sb.append(stName + "=" + stValue + "/n");
// }
}
sb.append("/n");
}
sb.append("-----------------遍历end-----------------/n");
System.out.println(sb.toString());

System.out.println("---------通过XPath获取一个元素----------");
Node node1 = document.selectSingleNode("/doc/person");
System.out.println("输出节点:" + "/t" + node1.asXML());

Node node2 = document.selectSingleNode("/doc/person/@sex");
System.out.println("输出节点:" + "/t" + node2.asXML());

Node node3 = document.selectSingleNode("/doc/person[name=/"原油/"]/age");
System.out.println("输出节点:" + "/t" + node3.asXML());

System.out.println("/n---------XPath获取List节点测试------------");
List list = document.selectNodes("/doc/person[name=/"猎猎/"]/adds/add");
for (Iterator it = list.iterator(); it.hasNext();) {
Node nodex = (Node) it.next();
System.out.println(nodex.asXML());
}

System.out.println("/n---------通过ID获取元素的测试----------");
System.out.println("陷阱:通过ID获取,元素ID属性名必须为“大写ID”,小写的“id”会认为是普通属性!");
String id22 = document.elementByID("22").asXML();
String id23 = document.elementByID("23").asXML();
String id24 = null;
if (document.elementByID("24") != null) {
id24 = document.elementByID("24").asXML();
} else {
id24 = "null";
}

System.out.println("id22= " + id22);
System.out.println("id23= " + id23);
System.out.println("id24= " + id24);
}

public static void main(String args[]) {
testParseXMLData("C://person.xml");
}

}
/**
* <?xml version="1.0" encoding="gb2312"?>
<doc>
<person id="1" sex="m">
<name>原油</name>
<age>32</age>
<adds>
<add code="wwww">homewww add</add>
<add code="hrttt">homettt add</add>
</adds>
</person>
<person id="2" sex="w">
<name>猎猎</name>
<age>90</age>
<adds>
<add ID="22" id="23" code="home">home add</add>
<add ID="23" id="22" code="com1">com1 add</add>
<add ID="24" id="24" code="com2">com2 add</add>
</adds>
</person>
</doc>
*/

只有main。没有类名!!!

/**
* <?xml version="1.0" encoding="utf-8"?>
<result>
<state value="1005"/>
<barcodeid value="-1" />
<inputcode value="-1" />
<barcodeurl value="http://www.gbsou.com" />
</result>
* @param args
* @throws Exception
*/
public static void main(String args[]) {
SAXReader saxReader = new SAXReader();
Document document = null;
FileInputStream fis = null;
try {
fis = new FileInputStream("C://testResult.xml");
document = saxReader.read(fis);
} catch (DocumentException e) {
System.out.println(e.getMessage());
System.out.println("读取classpath下xmlFileName文件发生异常,请检查CLASSPATH和文件名是否存在!");
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 通过根节点获取value值 这两个方法都可以得到value值一样的
String state = document.selectSingleNode("/result/state/@value").getStringValue();
String barcodeurl = document.selectSingleNode("/result/barcodeurl/@value").getStringValue();

String state = document.selectSingleNode("//state/@value").getStringValue();
String barcodeurl = document.selectSingleNode("//barcodeurl/@value").getStringValue();
System.out.println(state);
System.out.println(barcodeurl);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: