A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 从黑到白的马 中级黑马   /  2016-1-20 13:39  /  769 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

//DOm解析注意:这个方法以及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>
复制代码





0 个回复

您需要登录后才可以回帖 登录 | 加入黑马