JAVA中使用Dom解析XML

在G盘下新建XML文档:person.xml,XML代码:

<?xml version="1.0" encoding="utf-8"?>

<students> 
  <student id="1"> 
    <name>a</name>  
    <sex></sex>  
    <age>18</age> 
  </student>  
  <student id="2"> 
    <name>b</name>  
    <sex></sex>  
    <age>16</age> 
  </student> 
</students>

定义XML解析器的接口

package jichu;

public interface XmlParser {
    public void parseXml(String fileName);
}

XML解析器的实现

package jichu;

import java.io.FileNotFoundException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomXmlParser implements XmlParser {

    public void parseXml(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(fileName);
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            if (root != null) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node child = nodeList.item(i);
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.print("属性:");
                        System.out.println(child.getAttributes().getNamedItem(
                                "id"));
                    }
                    for (Node node = child.getFirstChild(); node != null; node = node
                            .getNextSibling()) {
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            System.out.print("子节点:");
                            System.out.println(node.getNodeName() + ":"
                                    + node.getTextContent());
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试:

package jichu;

public class MainClass {
    public static void main(String[] args) {
        XmlParser d = new DomXmlParser();
        d.parseXml("G:\\person.xml");
    }
}

打印:

属性:id="1"
子节点:name:a
子节点:sex:男
子节点:age:18
属性:id="2"
子节点:name:b
子节点:sex:女
子节点:age:16

 

posted @ 2017-03-09 15:23  SQP51312  阅读(288)  评论(0编辑  收藏  举报