DOM解析器演示使用DocumentBuilder。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DOM解析器演示使用DocumentBuilder。相关的知识,希望对你有一定的参考价值。

Code is to demonstrate the use of DocumentBuilder to parse the XML file. And retrieve the data from it.
  1. import java.io.File;
  2. import java.io.IOException;
  3.  
  4. import javax.xml.parsers.DocumentBuilder;
  5. import javax.xml.parsers.DocumentBuilderFactory;
  6. import javax.xml.parsers.ParserConfigurationException;
  7.  
  8. import org.w3c.dom.Document;
  9. import org.w3c.dom.Element;
  10. import org.w3c.dom.Node;
  11. import org.w3c.dom.NodeList;
  12. import org.xml.sax.SAXException;
  13.  
  14.  
  15. public class DocumentBuilderDemo {
  16.  
  17.  
  18. public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
  19. DocumentBuilder db = null;
  20. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  21. db = dbf.newDocumentBuilder();
  22. Document doc = db.parse(new File("c:\simple.xml"));
  23.  
  24. Element root = doc.getDocumentElement();
  25. System.out.println(root.getNodeName());
  26.  
  27. System.out.println("========================================================================");
  28.  
  29. NodeList nodeList = root.getElementsByTagName("to");
  30.  
  31. for (int i = 0; i < nodeList.getLength(); i++) {
  32. Node node = nodeList.item(i).getFirstChild();
  33. System.out.println(node.getNodeValue());
  34. }
  35.  
  36. System.out.println("========================================================================");
  37.  
  38. nodeList = root.getElementsByTagName("from");
  39.  
  40. for (int i = 0; i < nodeList.getLength(); i++) {
  41. Node node = nodeList.item(i).getFirstChild();
  42. System.out.println(node.getNodeValue());
  43. }
  44.  
  45. System.out.println("========================================================================");
  46.  
  47. nodeList = root.getElementsByTagName("body");
  48.  
  49. for (int i = 0; i < nodeList.getLength(); i++) {
  50. Node node = nodeList.item(i).getFirstChild();
  51. System.out.println(node.getNodeValue());
  52. }
  53.  
  54. System.out.println("========================================================================");
  55.  
  56.  
  57. }
  58.  
  59. }
  60.  
  61.  
  62. /*
  63. The simple.xml file that we used for parsing in above example.
  64.  
  65.  
  66. <?xml version="1.0"?>
  67. <msg>
  68. <note>
  69. <to>Tom</to>
  70. <from>Prince</from>
  71. <heading>Reminder</heading>
  72. <body>Hello how are u?</body>
  73. </note>
  74. <note>
  75. <to>Sania</to>
  76. <from>Prince</from>
  77. <heading>Joking</heading>
  78. <body>Welcome!!!</body>
  79. </note>
  80. </msg>
  81.  
  82. */

以上是关于DOM解析器演示使用DocumentBuilder。的主要内容,如果未能解决你的问题,请参考以下文章

使用DOM维护手机收藏信息

JAva使用DOM读取XML数据(解析)

DOM解析器解析增删改学习笔记

当我需要 DocumentBuilder 时使用 SAX 解析器

Java自带的XML解析器接口

Java解析XML三种常用方法