解析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){
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(
"xml文件的路径");
NodeList userList = doc.getElementsByTagName(
"user");
System.out.println(
"共有 "+userList.getLength()+
" 个user节点");
for(
int i =
0; i < userList.getLength(); i ++){
Node user = userList.item(i);
Element elem = (Element) user;
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();
}
}
}
}
}