黑马程序员技术交流社区

标题: DOM解析xml的步骤 [打印本页]

作者: 从黑到白的马    时间: 2016-1-20 13:39
标题: DOM解析xml的步骤
//DOm解析[qq]451704940[/qq]注意:这个方法以及sax解析的方法,学习Android的朋友可以当做了解内容,而学习javaweb的朋友需要掌握。
{:2_31:}

  1. package com.heima.parser;

  2. import javax.xml.parsers.DocumentBuilder;
  3. import javax.xml.parsers.DocumentBuilderFactory;

  4. import org.junit.Test;
  5. import org.w3c.dom.Document;
  6. import org.w3c.dom.NodeList;

  7. public class DomTest {
  8.         @Test
  9.         public void parser() throws Exception {
  10.                 // 获取工厂实例
  11.                 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
  12.                                 .newInstance();
  13.                 // 获取解析器对象
  14.                 DocumentBuilder newDocumentBuilder = documentBuilderFactory
  15.                                 .newDocumentBuilder();
  16.                 // 传入解析
  17.                 Document document = newDocumentBuilder.parse("XmlPerson.xml");
  18.                 NodeList list = document.getElementsByTagName("name");
  19.                 // 遍历
  20.                 for (int i = 0; i < list.getLength(); i++) {
  21.                         String name = list.item(i).getTextContent();
  22.                         System.out.println(name);
  23.                         /*
  24.                          * 数学书 英语书
  25.                          */
  26.                 }
  27.         }
  28. }
复制代码
//xml文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 222111111 -->
  3. <bookstore>
  4.         <book id="1">
  5.                 <name>数学书</name>
  6.                 <price>11</price>
  7.         </book>
  8.        
  9.         <book id="2">
  10.                 <name>英语书</name>
  11.                 <price>22</price>
  12.         </book>

  13. </bookstore>
复制代码










欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2