Java学习

java,spring,structs,hibernate,jsf,ireport,jfreechart,jasperreport,tomcat,jboss -----本博客已经搬家了,新的地址是 http://www.javaly.cn 如果有对文章有任何疑问或者有任何不懂的地方,欢迎到www.javaly.cn (Java乐园)指出,我会尽力帮助解决。一起进步

 

JAVA读取xml文件

  1. package com;   
  2.   
  3. import org.w3c.dom.*;  
  4. import javax.xml.parsers.*;  
  5. import java.io.*;  
  6.   
  7. public class Parse{  
  8.  //Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document 就意味着可以通过对  
  9.  //内存的操作来实现对XML的操作,首先第一步获取XML相关的Document  
  10.   private Document doc=null;  
  11.     
  12.  public void init(String xmlFile) throws Exception{  
  13.   //很明显该类是一个单例,先获取产生DocumentBuilder工厂  
  14.   //的工厂,在通过这个工厂产生一个DocumentBuilder,  
  15.   //DocumentBuilder就是用来产生Document的  
  16.   DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();  
  17.   DocumentBuilder db=dbf.newDocumentBuilder();    
  18.   //这个Document就是一个XML文件在内存中的镜像  
  19.   doc=db.parse(new File(xmlFile));  
  20.  }  
  21.  //该方法负责把XML文件的内容显示出来  
  22.  public void viewXML(String xmlFile) throws Exception{  
  23.   this.init(xmlFile);  
  24.   //在xml文件里,只有一个根元素,先把根元素拿出来看看  
  25.   Element element=doc.getDocumentElement();  
  26.   System.out.println("根元素为:"+element.getTagName());  
  27.     
  28.   NodeList nodeList=doc.getElementsByTagName("dbstore");  
  29.   System.out.println("dbstore节点链的长度:"+nodeList.getLength());  
  30.     
  31.   Node fatherNode=nodeList.item(0);  
  32.   System.out.println("父节点为:"+fatherNode.getNodeName());  
  33.     
  34.   //把父节点的属性拿出来  
  35.   NamedNodeMap attributes=fatherNode.getAttributes();  
  36.     
  37.   for(int i=0;i<attributes.getLength();i++){  
  38.    Node attribute=attributes.item(i);  
  39.    System.out.println("dbstore的属性名为:"+attribute.getNodeName()+" 相对应的属性值为:"+attribute.getNodeValue());  
  40.   }  
  41.   
  42.   NodeList childNodes = fatherNode.getChildNodes();  
  43.   System.out.println(childNodes.getLength());  
  44.   for(int j=0;j<childNodes.getLength();j++){  
  45.    Node childNode=childNodes.item(j);  
  46.    //如果这个节点属于Element ,再进行取值  
  47.    if(childNode instanceof Element){  
  48.     //System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());  
  49.     System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());  
  50.    }  
  51.   }  
  52.     
  53.  }  
  54.    
  55.  public static void main(String[] args)throws Exception{  
  56.   Parse parse=new Parse();  
  57.   
  58. //我的XML文件  
  59.   parse.viewXML("netct.xml");  
  60.  }  
  61. }  

posted on 2009-06-23 09:12 找个美女做老婆 阅读(217) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

公告

本blog已经搬到新家了, 新家:www.javaly.cn
 http://www.javaly.cn

常用链接

留言簿(6)

随笔档案

文章档案

搜索

最新评论

阅读排行榜

评论排行榜