dom4j解析xml文件
2013-09-11 15:07
573 查看
使用dom4j解析xml文件
xml文件如下:
Java代码:
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+""); } }
相关文章推荐
- dom4j 生成并解析xml文件
- dom4j解析XML文件
- java 利用dom4j 解析XML文件
- dom4j 对xml文件循环解析简单实例
- dom4j解析XML,生产XML,大文件XML
- dom4j创建xml文件,解析xml,写入xml文件,遍历xml文件
- 解析xml文件——dom4j
- Dom4J解析xml文件动态转换为List<Bean>或者Map集合
- Jdom和Dom4J解析xml文件
- java中采用dom4j解析xml文件
- JAVAEE--XML语言和DTD约束和解析xml文件方式DOM4J
- Dom4j解析带有命名空间的XML文件
- Dom4J --- 使用dom4j解析XML时候忽略DTD文件
- Dom4j解析xml文件-操作节点和属性及写入其他xml文件
- dom4j 解析xml文件
- dom4j解析XML文件
- dom4j解析xml文件
- dom4j解析xml文件基本操作
- dom4j解析XML文件(3)—XML文件写入
- DOM4J 解析XML文件