Java 解析XML

  1. packagecom.hxz.test;
  2. importjavax.xml.parsers.DocumentBuilder;
  3. importjavax.xml.parsers.DocumentBuilderFactory;
  4. importorg.w3c.dom.Document;
  5. importorg.w3c.dom.Element;
  6. importorg.w3c.dom.NodeList;
  7. /**
  8. *@authorybc
  9. *
  10. */
  11. publicclassTestXML{
  12. /**
  13. *@paramargs
  14. */
  15. publicstaticvoidmain(String[]args){
  16. TestXMLtest=newTestXML();
  17. test.testFile();
  18. }
  19. publicvoidtestFile(){
  20. Stringfilename="F://data//struts.xml";
  21. DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
  22. DocumentBuilderdb=null;
  23. Documentdoc=null;
  24. try{
  25. db=dbf.newDocumentBuilder();
  26. doc=db.parse(filename);
  27. }catch(Exceptione){
  28. System.out.println("打开文件错误:"+filename);
  29. e.printStackTrace();
  30. return;
  31. }
  32. Elementroot=doc.getDocumentElement();
  33. System.out.println("XML解析成功");
  34. NodeListybcList=root.getElementsByTagName("ybc");
  35. for(inti=0;i<ybcList.getLength();i++){
  36. Elementreport=(Element)ybcList.item(i);//返回一个Node
  37. Stringname=report.getAttribute("name").trim();
  38. Stringage=report.getAttribute("age");
  39. Stringaddress=report.getAttribute("address");
  40. System.out.println(name+"||"+age+"||"+address);
  41. }
  42. }
  43. }

你可能感兴趣的:(解析xml)