您的位置:首页 > 其它

dom4j解析xml文件

2013-09-11 15:07 573 查看
使用dom4j解析xml文件

xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<fruits name="水果" name2="还是水果">
<fruit name = "苹果">
<color>青色</color>
<price>3.5</price>
</fruit>
<fruit name = "梨">
<color>黄色</color>
<price>2.5</price>
</fruit>
</fruits>


Java代码:

/**
* 根据文件路径返回一个Document对象
* @param path
* @return
* @throws DocumentException
*/
public Document loadXML(String path) throws DocumentException{
SAXReader sax = new SAXReader();
Document docm = null;
docm = sax.read(path);
return docm;
}

public void sayXMl(String path) throws DocumentException{
Document docm = loadXML(path);
// 获取根节点
Element rootElt = docm.getRootElement();
//获取根节点名称
String rootName = rootElt.getName();
System.out.println("根节点名称:"+rootName);
System.out.println("根节点text:"+rootElt.getTextTrim());

//获取根节点的所有属性值集合
List list = rootElt.attributes();
for(Object ob:list){
Attribute temp = (Attribute) ob;
String str = temp.getName() + "-->value:" +temp.getValue();
System.out.println("根节点Attribute:"+str);
}

//获取根节点的所有的fruit节点的迭代
Iterator i = rootElt.elementIterator("fruit");
while(i.hasNext()){
Element itemEle = (Element) i.next();
//获取fruit节点下面的color节点的值
String color = itemEle.elementTextTrim("color");
//获取fruit节点下面的price节点的值
String price = itemEle.elementTextTrim("price");
//获取fruit节点的name属性值
String name = itemEle.attributeValue("name");
System.out.println("fruit:"+name+":  color-->"+color+"    price-->"+price+"");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: