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

分享非常有用的Java程序 (关键代码)(六)---解析/读取XML 文件(重要)

2015-07-11 14:18 1006 查看
原文:
分享非常有用的Java程序(关键代码)(六)---解析/读取XML文件(重要)

XML文件 <?xmlversion="1.0"?> <students> <student> <name>John</name> <grade>B</grade> <age>12</age> </student> <student> <name>Mary</name> <grade>A</grade> <age>11</age> </student> <student> <name>Simon</name> <grade>A</grade> <age>18</age> </student> </students>

Java解析的代码:

packagenet.viralpatel.java.xmlparser; importjava.io.File; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory; importorg.w3c.dom.Document; importorg.w3c.dom.Element; importorg.w3c.dom.Node; importorg.w3c.dom.NodeList; publicclassXMLParser{ publicvoidgetAllUserNames(StringfileName){ try{ DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance(); DocumentBuilderdb=dbf.newDocumentBuilder(); Filefile=newFile(fileName); if(file.exists()){ Documentdoc=db.parse(file); ElementdocEle=doc.getDocumentElement(); //Printrootelementofthedocument System.out.println("Rootelementofthedocument:"+docEle.getNodeName()); NodeListstudentList=docEle.getElementsByTagName("student"); //Printtotalstudentelementsindocument System.out.println("Totalstudents:"+studentList.getLength()); if(studentList!=null&&studentList.getLength()>0){ for(inti=0;i<studentList.getLength();i++){ Nodenode=studentList.item(i); if(node.getNodeType()==Node.ELEMENT_NODE){ System.out.println("====================="); Elemente=(Element)node; NodeListnodeList=e.getElementsByTagName("name"); System.out.println("Name:"+nodeList.item(0).getChildNodes().item(0).getNodeValue()); nodeList=e.getElementsByTagName("grade"); System.out.println("Grade:"+nodeList.item(0).getChildNodes().item(0).getNodeValue()); nodeList=e.getElementsByTagName("age"); System.out.println("Age:"+nodeList.item(0).getChildNodes().item(0).getNodeValue()); }} }else{ System.exit(1); }} }catch(Exceptione){ System.out.println(e); } } publicstaticvoidmain(String[]args){ XMLParserparser=newXMLParser(); } parser.getAllUserNames("c:\\test.xml"); } } }

版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: