Java 读取xml 文件

package com.xml;

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.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;

public class Test2 {  public static void main(String[] args) {   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   try {    DocumentBuilder db = dbf.newDocumentBuilder();    Document doc = db.parse("dogs.xml");    NodeList ndList = doc.getElementsByTagName("dog");    System.out.println("共找到"+ndList.getLength()+"节点");    Node dog ;    Element ele ;    //Node node ;    String name , value;    String arr = "" ;    for (int i = 0; i < ndList.getLength(); i++) {     dog= ndList.item(i);     ele = (Element)dog;     System.out.println(ele.getAttribute("dog"));     System.out.println("id:" + ele.getAttribute("id"));     for (Node node  =dog.getFirstChild(); node !=null; node = node.getNextSibling() ) {      if(node.getNodeType() == node.ELEMENT_NODE){      name = node.getNodeName();      value = node.getFirstChild().getNodeValue();      arr += node.getFirstChild().getNodeValue()+"#";      //Node n = node.cloneNode(true).getFirstChild();      //System.out.println(name+"\t"+value);      }     }    }    /*String [] ll = arr.split("#");    String sql ;    for (int i = 0; i < ll.length; i++) {     System.out.println(ll[4]);    }    System.out.println(arr);*/           } catch (ParserConfigurationException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (SAXException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  }

}

posted @ 2015-07-19 11:56  王南辉  阅读(91)  评论(0编辑  收藏  举报