java取出xml中某节点值,JAVA读取xml文件中节点值(转)
importorg.w3c.dom.*;importjavax.xml.parsers.*;importjava.io.*;publicclassParse{//Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document就意味着可以通过对//内存的操作来实现对XML的操作,首先第一步获取XML相关的DocumentprivateDocumentdoc=null;pub..
importorg.w3c.dom.*;importjavax.xml.parsers.*;importjava.io.*;publicclassParse{//Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document 就意味着可以通过对//内存的操作来实现对XML的操作,首先第一步获取XML相关的DocumentprivateDocument doc=null;publicvoidinit(String xmlFile)throwsException{//很明显该类是一个单例,先获取产生DocumentBuilder工厂//的工厂,在通过这个工厂产生一个DocumentBuilder,//DocumentBuilder就是用来产生Document的DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();//这个Document就是一个XML文件在内存中的镜像doc=db.parse(newFile(xmlFile));
}//该方法负责把XML文件的内容显示出来publicvoidviewXML(String xmlFile)throwsException{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(inti=0;i
Node attribute=attributes.item(i);
System.out.println("dbstore的属性名为:"+attribute.getNodeName()+"相对应的属性值为:"+attribute.getNodeValue());
}
NodeList childNodes=fatherNode.getChildNodes();
System.out.println(childNodes.getLength());for(intj=0;j
Node childNode=childNodes.item(j);//如果这个节点属于Element ,再进行取值if(childNodeinstanceofElement){//System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());
}
}
}publicstaticvoidmain(String[] args)throwsException{
Parse parse=newParse();//我的XML文件parse.viewXML("netct.xml");
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)