java读取xml

xiaoxiao2021-02-27  152

解析xml的步骤

创建DocumentBuilder工厂创建DocumentBuilder对象DocumentBuilder对象的parse方法得到Document对象Document对象的getElementsByTagName得到NodeList集合通过getFirstChild和getNextSibling进行遍历

用到的包

import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*;

需要的对象

DocumentBuilderFactory:创建DocumentBuilder的抽象工厂DocumentBuilder:可以从 XML 获取一个 DocumentDocument:提供供对文档数据的基本访问

xml文件内容

<?xml version="1.0" encoding="utf-8"?> <users> <user id="1"> <username>root</username> <password>123456</password> </user id="2"> <username>ordinay</username> <password>1111111</password> </user> </users> import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; public class ReadXml{ public static void main (String[]args){ //create a abstract factory DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try{ DocumentBuilder db = dbf.newDocumentBuilder(); //Gets a DOM object and returns it to the document object Document doc = db.parse("xml文件的路径"); //Gets a list of root elements NodeList userList = doc.getElementsByTagName("user"); //Traversal root element System.out.println("共有 "+userList.getLength()+" 个user节点"); for(int i = 0; i < userList.getLength(); i ++){ Node user = userList.item(i); Element elem = (Element) user; //Traversal root element sub node System.out.println("id:" + elem.getAttribute("id")); for(Node node = user.getFirstChild();node != null; node = node.getNextSibling()){ if (node.getNodeType() == Node.ELEMENT_NODE) { String name = node.getNodeName(); String value = node.getFirstChild().getNodeValue(); System.out.print(name + ":" + value + "\t"); } System.out.println(); } } } } }
转载请注明原文地址: https://www.6miu.com/read-16085.html

最新回复(0)