Java&Xml教程(二)使用DOM方式解析XML文件
DOM XML 解析方式是最容易理解的,它將XML文件作为Document对象读取到内存中,然后你可以轻松地遍历不同的元素和节点对象。遍历元素和节点不需要按照顺序进行。
DOM解析方式适合尺寸较小的XML文件,由于它將整个XML文件全部装载到内存中处理,所以不太适合处理尺寸较大的XML文件。对于较大的XML文件需要使用SAX解析。
在本教程中我们将对XML文件读取和解析,并用它来创建对象。下面是我们将要解析的XML文件。
employee.xml
<?xml version="1.0"?>
<Employees>
<Employee>
<name>Pankaj</name>
<age>29</age>
<role>Java Developer</role>
<gender>Male</gender>
</Employee>
<Employee>
<name>Lisa</name>
<age>35</age>
<role>CSS Developer</role>
<gender>Female</gender>
</Employee>
</Employees>
这个XML文件的内容是一些员工信息列表,因此我们需要创建一个Employee类来表示员工,然后將XML文件信息读取到程序中。
下面是Employee类的定义:
package com.journaldev.xml;
public class Employee {
private String name;
private String gender;
private int age;
private String role;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +
" Role=" + this.role;
}
}
需要注意的是这里我重写了toString()方法以便打印出员工对象的有用信息。接下来我们在程序中使用DOM解析方式读取XML文件来获取Employee 对象列表。
XMLReaderDOM.java
package com.journaldev.xml;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLReaderDOM {
public static void main(String[] args) {
String filePath = "employee.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("Employee");
//now XML is loaded as Document in memory, lets convert it to Object List
List<Employee> empList = new ArrayList<Employee>();
for (int i = 0; i < nodeList.getLength(); i++) {
empList.add(getEmployee(nodeList.item(i)));
}
//lets print Employee list information
for (Employee emp : empList) {
System.out.println(emp.toString());
}
} catch (SAXException | ParserConfigurationException | IOException e1) {
e1.printStackTrace();
}
}
private static Employee getEmployee(Node node) {
//XMLReaderDOM domReader = new XMLReaderDOM();
Employee emp = new Employee();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
emp.setName(getTagValue("name", element));
emp.setAge(Integer.parseInt(getTagValue("age", element)));
emp.setGender(getTagValue("gender", element));
emp.setRole(getTagValue("role", element));
}
return emp;
}
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
}
程序输出内容如下:
Root element :Employees
Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer
Employee:: Name=Lisa Age=35 Gender=Female Role=CSS Developer
在实际情况下,我们在解析XML文件之前先要对XML文件的合法性进行校验,学习如何使用XSD校验XML文件。
原文地址:http://www.journaldev.com/898/how-to-read-an-xml-file-in-java-dom-parser
Java&Xml教程(二)使用DOM方式解析XML文件的更多相关文章
- 用JAXP的dom方式解析XML文件
用JAXP的dom方式解析XML文件,实现增删改查操作 dom方式解析XML原理 XML文件 <?xml version="1.0" encoding="UTF-8 ...
- 用DOM方式解析XML
一.用DOM方式解析XML 此例子节点结构如下: 1.获取book节点属性 (1).如果不知道节点的属性,通过 NamedNodeMap attrs = book.getAttributes(); 来 ...
- Dom方式解析XML
public class TestXML { public static void main(String[] args) throws SAXException, IOException { //D ...
- 在iOS 开发中用GDataXML(DOM方式)解析xml文件
因为GDataXML的内部实现是通过DOM方式解析的,而在iOS 开发中用DOM方式解析xml文件,这个时候我们需要开启DOM,因为ios 开发中是不会自动开启的,只有在mac 开发中才自动开启的.我 ...
- Java眼中的XML--文件读取--1 应用DOM方式解析XML
初次邂逅XML: 需要解析的XML文件: 这里有两个book子节点. 1.如何进行XML文件解析前的准备工作,另外解析先获取book节点. 这个我后来看懂了: 这个Node的ELEMENT_NODE= ...
- Java-Web DOM方式解析xml文件
XML DOM 树形结构: DOM 节点 根据 DOM,XML 文档中的每个成分都是一个节点. DOM 是这样规定的: 整个文档是一个文档节点 每个 XML 元素是一个元素节点 包含在 XML 元素中 ...
- DOM方式解析xml实例2
老样子,javabean实体类: import java.io.*; public class Book implements Serializable { private int id; priva ...
- Java DOM方式解析XML(模板)
//创建一个DocumentBuilderFactory工厂实例 DocumentBuilderFactory DBF=DocumentBuilderFactory.newInstance(); // ...
- DOM方式解析XML文件实例
books.XML文件: <?xml version="1.0" encoding="utf-8"?><bookstore> &l ...
随机推荐
- [luoguP1026] 统计单词个数(DP)
传送门 题解 #include <cstdio> #include <cstring> #define max(x, y) ((x) > (y) ? (x) : (y)) ...
- sql语句的字段转成Date
ms_sql:convert(datetime,'2010-11-13')cast('2017-01-01' as datetime) Oracle:to_date('2017-01-01') mys ...
- python函数基础:嵌套函数、作用域、匿名函数、高阶函数、递归函数
嵌套函数: 1. 函数内部可以再定义函数 2. 函数只有被调用之后才会执行 看如下代码: age = 18 def func1(): age = 22 print(age) def func2(): ...
- php处理管道文件流
<?php #!/usr/local/bin/php -q function read(){ $fp = fopen("php://stdin", "r" ...
- 浅谈SQL Server 对于内存的管理--宋沄剑 英文名:CareySo
http://www.cnblogs.com/CareySon/archive/2012/08/16/HowSQLServerManageMemory.html
- gem5: 使用ruby memory system中的mesh结构 出现AssertionError错误
问题:在使用ruby memory system中的mesh结构測试时,出现例如以下错误: Traceback (most recent call last): File "<stri ...
- 查看程序占用tomcat内存情况
近期,公司线上tomcat常常无缘无辜宕机.总结了一下定位问题的方法,仅供參考: 报错信息: Maximum number of threads (200) created for connector ...
- 转 C# 将字符串转换为计算公式,并计算结果
根据总结,大概分为以下三种: 第一种: 用DataTable中的Compute方法. 例如:" 1*2*3 " 代码如下: var a = new System.Data.Data ...
- objc_setAssociatedObject 1
[Objective-C]关联(objc_setAssociatedObject.objc_getAssociatedObject.objc_removeAssociatedObjects) 标签: ...
- 1250 Fibonacci数列
1250 Fibonacci数列 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题解 查看运行结果 题目描述 Description 定义:f ...