java如何解析/读取xml文件
本文实例为大家分享了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"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助。