xml解析
发布时间:2020-12-16 05:54:08 所属栏目:百科 来源:网络整理
导读:import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class XmlTest {p
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XmlTest { public void getAllUserName(String fileName){ try { /* * 1、获得DOM解析器工厂类 * 2、得到DOM解析器 * 3、得到xml文件File * 4、解析xml文件获得Document对象 * 5、得到xml文件的根节点 * 6、得到根节点下的所有子节点 */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); File file = new File(fileName); if(file.exists()){ Document doc = db.parse(file); Element e = doc.getDocumentElement(); System.out.println("root document:"+e.getNodeName()); NodeList nodeList = e.getElementsByTagName("student"); if(nodeList!=null&&nodeList.getLength()>0){ for(int i=0;i<nodeList.getLength();i++){ //7、循环节点 Node node = nodeList.item(i); if(node.getNodeType()==Node.ELEMENT_NODE){ System.out.println("======开始解析====="); Element nameE = (Element)node; NodeList nameNodeList= nameE.getElementsByTagName("name"); System.out.println("name:"+nameNodeList.item(0).getChildNodes().item(0).getNodeValue()); Element gradeE = (Element)node; NodeList gradeNodeList= gradeE.getElementsByTagName("grade"); System.out.println("grade:"+gradeNodeList.item(0).getChildNodes().item(0).getNodeValue()); Element ageE = (Element)node; NodeList ageNodeList= ageE.getElementsByTagName("age"); System.out.println("age:"+ageNodeList.item(0).getChildNodes().item(0).getNodeValue()); } } }else{ System.exit(1); } } } catch(Exception e){ } } public static void main(String[] args) { XmlTest xt = new XmlTest(); xt.getAllUserName("e:test.xml"); } } xml文件内容 <?xml version="1.0"?> <students> <student> <name>111</name> <grade>B</grade> <age>23</age> </student> <student> <name>222</name> <grade>A</grade> <age>24</age> </student> <student> <name>333</name> <grade>A</grade> <age>25</age> </student> </students> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – ActiveRecord :: EagerLoadPolymorphicEr
- C#Combobox(Dropdownstyle =简单) – 如何在键入时选择项目
- 使用ajax实现动态局部刷新
- c# – foreach如何在没有显式/隐式覆盖的情况下进行转换?
- bboss aop/ioc依赖注入功能介绍
- ruby-on-rails – Ruby – 通过嵌套属性选择属于两个数组的
- c# – 根据后代节点的属性选择节点的最佳LINQ-to-XML查询?
- arrays – 使用关联值映射swift枚举
- ReactiveCocoa Unknown warning group ‘-Wreceiver-is-wea
- C#如何在Outlook加载项中发送代表电子邮件地址