JAVA技巧:dom解析xml文件實現(xiàn)代碼

字號:

代碼如下:
    package com.yangrs;
    import java.io.IOException;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    public class DomTest {
    public static void main(String[] args) {
    try {
    javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory
    .newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document dom = db.parse("myxml1.xml");
    System.out.println("文件路徑:" + dom.getDocumentURI());
    org.w3c.dom.Element root = dom.getDocumentElement();
    Iterator(root); //循環(huán)迭代
    // for(int i = 0; i < nodelist.getLength(); i++) {
    // System.out.println(nodelist.item(i).getNodeName());
    // System.out.println(nodelist.item(i).getNodeValue());
    // System.out.println(nodelist.item(i).getTextContent());//這里才取得了每個結點的值
    //
    // //會有七個節(jié)點,because空格也算
    // NodeList childlist = nodelist.item(i).getChildNodes();
    //
    // for(int j = 0; j < childlist.getLength();j++) {
    // System.out.println(childlist.item(j).getNodeName());
    // }
    //
    // }
    } catch (ParserConfigurationException e) {
    e.printStackTrace();
    } catch (SAXException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    /**
    * 做循環(huán)使用
    *
    * @param root
    * 傳入的元素
    */
    public static void Iterator(Element root) {
    NodeList nodelist = root.getChildNodes();
    for (int i = 0; i < nodelist.getLength(); i++) {
    Node node = nodelist.item(i);
    if (node instanceof Text) {
    String value = node.getNodeValue();
    if (value != null && !value.trim().equals("")) {
    System.out.println("文本:" + value);
    }
    }
    if (node instanceof Element) {
    System.out.println("節(jié)點:" + node.getNodeName());
    Iterator((Element) node);
    }
    }
    }