黑马程序员技术交流社区
标题:
DOM解析xml的步骤
[打印本页]
作者:
从黑到白的马
时间:
2016-1-20 13:39
标题:
DOM解析xml的步骤
//DOm解析[qq]451704940[/qq]
注意:这个方法以及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>
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2