一、新建一个demo.xml的文件:
- <? xml version="1.0" encoding="UTF-8" ?>
- <bookstore>
- <book id="1">
- <name>放学后</name>
- <author>cmirssd</author>
- <year>2010</year>
- <price>25</price>
- </book>
-
- <book id="2">
- <name>你的孤独,虽败犹荣</name>
- <author>刘同</author>
- <year>2011</year>
- <price>30</price>
- </book>
- </bookstore>
使用DOM的准备工作:
1、创建DocumentBuilderFactory对象(newInstance方法)
2、创建DocumentBuilder对象(newDocumentBuilder方法)
3、DocumentBuilder对象的parse()方法
新建一个Xmltest.java,代码如下:
- package com.imooc.io;
-
- import java.io.IOException;
-
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
-
- import org.w3c.dom.Document;
- import org.w3c.dom.NamedNodeMap;
- import org.w3c.dom.Node;
- import org.w3c.dom.NodeList;
- import org.xml.sax.SAXException;
-
- public class Xmltest {
- public static void main(String[] args){
- Xmltest t = new Xmltest();
- t.readXML();
- }
-
- public void readXML(){
-
- DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();
- try {
-
- DocumentBuilder b = a.newDocumentBuilder();
-
- Document document = b.parse("demo.xml");
-
- NodeList booklist = document.getElementsByTagName("book");
- for(int i =0; i<booklist.getLength(); i++){
-
- Node book = booklist.item(i);
-
- NamedNodeMap bookmap = book.getAttributes();
-
- for(int j = 0; j<bookmap.getLength(); j++){
- Node node = bookmap.item(j);
-
- System.out.println(node.getNodeName());
- System.out.println(node.getNodeValue());
- }
- NodeList childlist = book.getChildNodes();
- for(int t = 0; t<childlist.getLength(); t++){
-
- if(childlist.item(t).getNodeType() == Node.ELEMENT_NODE){
- System.out.println(childlist.item(t).getNodeName());
-
-
- System.out.println(childlist.item(t).getTextContent());
-
-
-
- }
- }
- }
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
其中获取子节点值得方法有:getTextContent()和getFirstChild().getNodeValue()方法。
区别是:
1、如果子节点里面还嵌套着子节点,如:<name><a>www</a>放学后</name>,getTextContent()方法能够一起输出:www放学后
2、如果子节点里面嵌套这子节点,如:<name><a>www</a>放学后</name>,则会输出null
运行结果:
id
1
name
放学后
author
lcb
year
2010
price
25
id
2
name
你的孤独,虽败犹荣
author
刘同
year
2011
price
30