以解析NewFile.xml 中的数据为例
import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ParseXML{ public static void main(String[] args) throws Exceptions{ SAXReader reader = new SAXReader(); Document document = reader.read("src/NewFile.xml"); Element root = document.getRootElement(); Iterator<Element> it = root.elementIterator(); //在本例中, 获取到了根元素, goodslist while(it.hasNext()){ Element ele = it.next(); //在本例中, 获取到了第一个子元素, good
/* 获取指定标签下的指定标签 */
if(ele.getName().equals("good")) // 检查元素名称是否为good
{
Element name = ele.element("name"); //获取到了good下名字为name(商品名称)的元素
if(name != null)
System.out.println(name.getText()); //输出商品名称的内容
}
System.out.println(ele.getName()); Iterator<Attribute> attributes = ele.attributeIterator(); while(attributes.hasNext()){ Attribute ab = attribute.next(); System.out.println(ab.getName()+":"+ab.getValue()); } }
/*
Element ele = null;
ele.elementIterator("good"); //遍历所有名字为good的子元素
Attribute ab = null;
ab.getName(); //获取属性的名字
ab.getValue(); //获取属性的值
ab.getDocument(); //得到所在的文档对象
*/
}
}
/* Output:
香蕉
good
id:1001
production_date:2018-4-1
苹果
good
id:1002
...
*/
NewFile.xml
<?xml version="1.0" encoding="UTF-8"?> <goodslist> <good id="1001" production_date="2018-4-1"> <price>12</price> <name>香蕉</name> <place>广州</place> </good> <good id="1002"> <price>39</price> <name>苹果</name> <place>北京</place> </good> <good id="1003"> <price>33</price> <name>芒果</name> <place>上海</place> </good> </goodslist>