dom4j解析xml实例(2)
dom4j是一个java的XML API,类似jdom,用来读写XML文件,它性能优异、功能强大和极易使用等特点
所用jar包:dom4j-1.6.1.jar、jaxen-1.1-beta-6.jar
需要解析的xml文件:people.xml
1 2 3 4 5 6 | <people city= "shenzhen" > <student name= "milton" age= "22" ></student> <student name= "lego" age= "23" ></student> <teacher name= "bruce" age= "27" ></teacher> <teacher name= "ziven" age= "28" ></teacher> </people> |
java代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package demo5; import java.io.File; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Test01 { public static void main(String args[]) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read( new File( "D:/people.xml" )); Element rootElm = document.getRootElement(); //Element root1Elm = rootElm.element("city"); @SuppressWarnings ( "rawtypes" ) List nodes = rootElm.elements( "student" ); @SuppressWarnings ( "rawtypes" ) List nodess = rootElm.elements( "teacher" ); for ( @SuppressWarnings ( "rawtypes" ) Iterator it = nodes.iterator(); it.hasNext();) { Element elm = (Element) it.next(); System.out.println( "name:" + elm.attributeValue( "name" ) + " age:" + elm.attributeValue( "age" )); } for ( @SuppressWarnings ( "rawtypes" ) Iterator it = nodess.iterator(); it.hasNext();) { Element elm = (Element) it.next(); System.out.println( "name:" + elm.attributeValue( "name" ) + " age:" + elm.attributeValue( "age" )); } System.out.println(); try { Document doc = reader.read( new File( "D:/people.xml" )); @SuppressWarnings ( "rawtypes" ) List projects = doc.selectNodes( "people/student" ); @SuppressWarnings ( "rawtypes" ) List projectss = doc.selectNodes( "people/teacher" ); @SuppressWarnings ( "rawtypes" ) Iterator it = projects.iterator(); while (it.hasNext()) { Element elm = (Element) it.next(); System.out.println( "name:" + elm.attributeValue( "name" ) + " age:" + elm.attributeValue( "age" )); } @SuppressWarnings ( "rawtypes" ) Iterator its = projectss.iterator(); while (its.hasNext()) { Element elm = (Element) its.next(); System.out.println( "name:" + elm.attributeValue( "name" ) + " age:" + elm.attributeValue( "age" )); } } catch (Exception ex) { ex.printStackTrace(); } } } |
代码运行后结果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix