dom解析xml文件实现代码
来源:优易学  2011-12-22 19:30:44   【优易学:中国教育考试门户网】   资料下载   IT书店
  代码如下:
  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); //循环迭代
  // 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());//这里才取得了每个结点的值
  //
  // //会有七个节点,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();
  }
  }
  /**
  * 做循环使用
  *
  * @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("节点:" + node.getNodeName());
  Iterator((Element) node);
  }
  }
  }
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训