java解析xml文件
程序员文章站
2022-06-17 08:25:47
...
JDK API中提供了3种方式解析XML,分别为DOM、SAX、XPath。
目录:
- DOM
- XPath:Mybaties中采用XPath方式解析XML文件的配置信息。
- SAX
一.DOM
studentx.xml
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
XMLParser.java
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 XMLParser {
public void getAllUserNames(String fileName) {
try {
//1.获得一个文档解析器工厂:定义工厂API,使应用程序能够从XML文档获取生成DOM对象树的解析器
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//2.获得一个文档解析器:定义从XML文档获取DOM文档实例的API。 使用这个类,应用程序员可以从XML获得一个Document 。
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
//3.解析器解析xmL文件,获得一个DOM文档
Document doc = db.parse(file);
//4.通过DOM文档获取根结点元素,并打印
Element docEle = doc.getDocumentElement();
System.out.println("Root element of the document: "+ docEle.getNodeName());
//5.通过DOM文档根据标签名获取所有其对应的结点,并将其存储在NodeList抽象集合中
NodeList studentList = docEle.getElementsByTagName("student");
System.out.println("Total students: " + studentList.getLength());
//6.打印"student"结点下所有的结点信息
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
//7.遍历一个"student"结点
Node node = studentList.item(i);
//8.node.getNodeType() == Node.ELEMENT_NODE,表示node结点是一个Element(一组)
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("=====================");
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "+nodeList.item(0).getChildNodes().item(0) .getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());
}
}
} else {
;
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("./src/students.xml");
}
}
三.XPath方式
users.xml
<?xml version="1.0"?>
<users>
<user id="1">
<name>张三</name>
<createTime>2018-10-15</createTime>
<password>123</password>
<phone>10086</phone>
<nickName>阿毛</nickName>
</user>
<user id="2">
<name>李四</name>
<createTime>2018-10-15</createTime>
<password>234</password>
<phone>12306</phone>
<nickName>二狗子</nickName>
</user>
</users>
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UserEntity {
private Long id;
private String name;
private Date createTime;
private String password;
private String phone;
private String nickName;
static UserEntity buildUserEntity(String id, String name, String createTime, String password, String phone,
String nickName) throws ParseException {
UserEntity user=new UserEntity();
user.id=Long.valueOf(id);
user.name=name;
user.createTime=new SimpleDateFormat("yyyy-MM-dd").parse(createTime);
user.password=password;
user.nickName=nickName;
return user;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return id+"-"+name+"-"+createTime+"-"+password+"-"+nickName;
}
}
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLParser {
public void getAllUserNames(String fileName) {
try {
//1.获得一个文档解析器工厂:定义工厂API,使应用程序能够从XML文档获取生成DOM对象树的解析器
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//2.获得一个文档解析器:定义从XML文档获取DOM文档实例的API。 使用这个类,应用程序员可以从XML获得一个Document 。
DocumentBuilder builder = dbf.newDocumentBuilder();
File file=new File(fileName);
//3.通过解析器解析xml文件,获得一个文档对象
Document document=builder.parse(file);
//4.获取新的XPathFactory实例
XPathFactory xpathFactory=XPathFactory.newInstance();
//5.一个XPathFactory实例可以用来创建XPath对象
XPath xpath=xpathFactory.newXPath();
//6.xpath根据根结点"users"标签解析document文档
NodeList nodeList=(NodeList) xpath.evaluate("/users/*", document,XPathConstants.NODESET);
//7.获取一个ArrayList实例用来存储UserEntity对象
List<UserEntity> userList=new ArrayList<UserEntity>();
//8.获取所有的user结点
for(int i=1;i<nodeList.getLength()+1;i++) {
String path="/users/user["+i+"]";
String id=(String) xpath.evaluate(path+"/@id", document,XPathConstants.STRING);
String name=(String) xpath.evaluate(path+"/name", document,XPathConstants.STRING);
String createTime=(String) xpath.evaluate(path+"/createTime", document,XPathConstants.STRING);
String password=(String) xpath.evaluate(path+"/password", document,XPathConstants.STRING);
String phone=(String) xpath.evaluate(path+"/phone", document,XPathConstants.STRING);
String nickName=(String) xpath.evaluate(path+"/nickName", document,XPathConstants.STRING);
//调用buildUserEntity()方法构建UserEntity对象
UserEntity userEntity=UserEntity.buildUserEntity(id,name,createTime,password,phone,nickName);
userList.add(userEntity);
}
for(UserEntity user:userList) {
System.out.println(user);
}
}catch(Exception e){
e.getMessage();
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("./src/users.xml");
}
}
上一篇: JS高级回顾——第五篇
下一篇: 第五篇:python基础_5