//DOm解析注意:这个方法以及sax解析的方法,学习Android的朋友可以当做了解内容,而学习javaweb的朋友需要掌握。
{:2_31:}
- package com.heima.parser;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import org.junit.Test;
- import org.w3c.dom.Document;
- import org.w3c.dom.NodeList;
- public class DomTest {
- @Test
- public void parser() throws Exception {
- // 获取工厂实例
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
- .newInstance();
- // 获取解析器对象
- DocumentBuilder newDocumentBuilder = documentBuilderFactory
- .newDocumentBuilder();
- // 传入解析
- Document document = newDocumentBuilder.parse("XmlPerson.xml");
- NodeList list = document.getElementsByTagName("name");
- // 遍历
- for (int i = 0; i < list.getLength(); i++) {
- String name = list.item(i).getTextContent();
- System.out.println(name);
- /*
- * 数学书 英语书
- */
- }
- }
- }
复制代码 //xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <!-- 222111111 -->
- <bookstore>
- <book id="1">
- <name>数学书</name>
- <price>11</price>
- </book>
-
- <book id="2">
- <name>英语书</name>
- <price>22</price>
- </book>
- </bookstore>
复制代码
|
|