技术中心

这里象征着我们的态度和能力

>JAVA读取xml文件中节点值
发布者:中国IT实验室    信息来源:中国IT实验室    发布时间:2012-01-09      浏览次数:6184
分享到:

新浪微博

腾讯微博

QQ空间

豆瓣网

QQ好友

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  import org.w3c.dom.*;

  import javax.xml.parsers.*;

  import java.io.*;

  public class Parse{

  //Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document 就意味着可以通过对

  //内存的操作来实现对XML的操作,首先第一步获取XML相关的Document

  private Document doc=null;

  public void init(String xmlFile) throws Exception{

  //很明显该类是一个单例,先获取产生DocumentBuilder工厂

  //的工厂,在通过这个工厂产生一个DocumentBuilder,

  //DocumentBuilder就是用来产生Document的

  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

  DocumentBuilder db=dbf.newDocumentBuilder();

  //这个Document就是一个XML文件在内存中的镜像

  doc=db.parse(new File(xmlFile));

  }

  //该方法负责把XML文件的内容显示出来

  public void viewXML(String xmlFile) throws Exception{

  this.init(xmlFile);

  //在xml文件里,只有一个根元素,先把根元素拿出来看看

  Element element=doc.getDocumentElement();

  System.out.println("根元素为:"+element.getTagName());

  NodeList nodeList=doc.getElementsByTagName("dbstore");

  System.out.println("dbstore节点链的长度:"+nodeList.getLength());

  Node fatherNode=nodeList.item(0);

  System.out.println("父节点为:"+fatherNode.getNodeName());

  //把父节点的属性拿出来

  NamedNodeMap attributes=fatherNode.getAttributes();

  for(int i=0;i<attributes.getLength();i++){

  Node attribute=attributes.item(i);

  System.out.println("dbstore的属性名为:"+attribute.getNodeName()+" 相对应的属性值为:"+attribute.getNodeValue());

  }

  NodeList childNodes = fatherNode.getChildNodes();

  System.out.println(childNodes.getLength());

  for(int j=0;j<childNodes.getLength();j++){

  Node childNode=childNodes.item(j);

  //如果这个节点属于Element ,再进行取值

  if(childNode instanceof Element){

  //System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());

  System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());

  }

  }

  }

  public static void main(String[] args)throws Exception{

  Parse parse=new Parse();

  //我的XML文件

  parse.viewXML("netct.xml");

  }

  }

4000-880-989
(24小时热线)
联系客服
微信公众号

官方公众号

小程序

©2008-2022 CORPORATION ALL Rights Reserved. 昆明奥远科技有限公司版权所有 滇ICP备09003328号-1 滇公网安备 53011102000818号
昆明那家网络公司好,新媒体运营,网站优化,网络推广,网站建设,网页设计,网站设计,网站推广,云南网站公司,昆明新媒体公司,云南网红主播,昆明SEO公司,昆明网站建设,昆明网络推广,昆明网站优化,昆明网站推广,红河网站建设,大理网络公司,曲靖网络公司,丽江网站设计,昭通网络公司,保山大数据服务,智慧高速建设,智慧校园服务,云南IDC服务商,网络安全测评,等保测评,网站关键词排名优化服务,服务客户尽超2000余家,一切尽在奥远科技,服务电话:13888956730