DOMTest
读API步骤,先看包,再看类,再读类下面的方法,要注意方法需要的参数和返回值,边用边理解.
package com.qiuhu;
/*import javax.lang.model.element.Element;*/
import javax.swing.text.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.Node;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
public class DiskDom {
public static void main(String[] args) throws Exception {
//创建解析工厂
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
//创建解析器
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document document=builder.parse("src/com/qiuhu/disk.xml");
NodeList nodes=document.getElementsByTagName("disk");
org.w3c.dom.Node node=nodes.item(0);
org.w3c.dom.Node n1=node.getFirstChild();
org.w3c.dom.Node n2=n1.getNextSibling();
org.w3c.dom.Node n3=node.getLastChild();
NamedNodeMap attribut=node.getAttributes();
org.w3c.dom.Node n4=attribut.item(0);
/* String n=node.getFirstChild().getNodeValue();*/
System.out.println( "disk"+n4.getNodeValue()+
"size"+n1.getFirstChild()+
"dirctory"+n2.getFirstChild()+
"File"+n3.getFirstChild());
}
}
先用XML文档写出相关文件
<?xml version="1.0" encoding="UTF-8"?>
<disks>
<disk name="C盘">
<size>10G</size>
<dirctory>10</dirctory>
<file>30</file>
</disk>
<disk name="D盘">
<size>10G</size>
<dircetory>10</directory>
<file>20</file>
</disk>
</disks>
参照API,先得到解析工厂,在构造解析器,再使用相关方法读取,代码如下:
package com.qiuhu;
import javax . xml. parsers. DocumentBuilder ;
import javax . xml. parsers . DocumentBuilderFactory;
import javax.xml.soap.Node;
import org .w3c . dom. Document;
import org. w3c. dom. Element;
import org. w3c. dom. NodeList;
public class DiskDom1 {
public static void main(String[] args) throws Exception {
//
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
//
DocumentBuilder builder =factory.newDocumentBuilder();
Document document=builder.parse("C:\\Users\\daier\\eclipse-workspace\\Project1\\src\\com\\qiuhu\\disk.xml");
NodeList n1 =document . getElementsByTagName("disk");
for(int i=0;i<n1. getLength();i++) {
Element e=(Element)n1. item(i);
System. out. print( "磁盘: "+e. getAttribute("name")+" ");
System.out.print( "大小:"+e.getElementsByTagName("size"). item(0).getFirstChild().getNodeValue());
System.out.print("文件:"+e.getElementsByTagName("directory").item(0). getFirstChild().getNodeValue());
System.out.print( "目录:"+e.getElementsByTagName ("file").item(0).getFirstChild().getNodeValue());
}
}
}
DOM实际读取
上面方法是我们已经知道几乎所有的节点是什么才进行的遍历,实际上,在很大的文档上几乎不可能用上述方法遍历.故而如下:
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="1" depName="教学部">
<name>rose</name>
<age>22</age>
<agender>female</agender>
<email>rose@briup.com</email>
<salary>8k</salary>
</employee>
<employee id="2" depName="教学部">
<name>jack</name>
<age>23</age>
<agender>male</agender>
<email>jack@briup.com</email>
<salary>9k</salary>
</employee>
</employees>
先构造Empoyee类,用来存放阅读XML节点内容
package com.qiuhu;
public class Employee {
private int id;
private String depName;
private String name;
private int age;
private String gender;
private String email;
private String salary;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(int id, String depName, String name, int age, String gender, String email, String salary) {
super();
this.id = id;
this.depName = depName;
this.name = name;
this.age = age;
this.gender = gender;
this.email = email;
this.salary = salary;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the depName
*/
public String getDepName() {
return depName;
}
/**
* @param depName the depName to set
*/
public void setDepName(String depName) {
this.depName = depName;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the salary
*/
public String getSalary() {
return salary;
}
/**
* @param salary the salary to set
*/
public void setSalary(String salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", depName=" + depName + ", name=" + name + ", age=" + age + ", gender=" + gender
+ ", email=" + email + ", salary=" + salary + "]";
}
}
如旧解析工厂解析器,其后遍历时将得到的元素节点的值赋予上一个类的相关值.即先确定节点的name,再确定其节点后续所有的文字信息value
package com.qiuhu;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DomEmployee {
//存放数据
private static Employee employee;
private static List<Employee> list=new ArrayList<Employee>();
public static void main(String[] args) throws Exception {
//构建解析工厂
DocumentBuilderFactory factory=
DocumentBuilderFactory.newInstance();
//构建解析器
DocumentBuilder builder =factory.newDocumentBuilder();//此处会抛出异常
Document document=builder.parse("Project1/src/com/qiuhu/employee.xml");
//直接读取employee标签,构建employeeduixiang
NodeList n1=document.getElementsByTagName("employee");
for(int i=1;i<n1.getLength();i++) {
//遍历一个employee标签,构建一个employee对象
Employee employee=new Employee();
//将node转换成element节点
Element element=(Element) n1.item(i);
int id=Integer.parseInt(element.getAttribute("id"));//API定义好的方法
String depName=element.getAttribute("depName");
System.out.println("id"+id+"depName"+depName);
employee.setDepName(depName);
employee.setId(id);
//获取employee节点的所有子节点,name age gender元素节点 不要换行之类的文本节点
NodeList n12=element.getChildNodes();
for (int j = 0; j < n12.getLength(); j++) {
if(n12.item(j).getNodeType()==1) {
String name=n12.item(j).getNodeName();
String value=n12.item(j).getTextContent();
if ("name".equals(name)) {
employee.setName(value);
}else if("gender".equals(name)){
employee.setGender(value);
}else if("name".equals(name)){
employee.setAge(Integer.parseInt(value));
}
}
}
list.add(employee);
}
System.out.println("保存的用户数"+list.size());
}
}
SAX处理
package com.qiuhu;
import javax.crypto.spec.DHGenParameterSpec;
import javax.swing.text.html.HTMLEditorKit.Parser;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class DiskSAx {
public static void main(String[] args) throws Exception {
//创建SAX的解析工厂
SAXParserFactory factory=
SAXParserFactory.newInstance();
//创建SAX的解析器
SAXParser parser=factory.newSAXParser();
//相对路径不以"/"开头
//第一个参数为解析的文件,第二个参数才是需要解析的
parser.parse("src/com/qiuhu/NewFile.xml",new MyHandler());
}
}
class MyHandler extends DefaultHandler{
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
/**
* 前两个参数提供网络应用,暂时不需要考虑
* qName:表示标签名
* attribute:表示标签属性
*/
System.out.print("<"+qName);
//输出属性内容
for (int i = 0; i < attributes.getLength(); i++) {
String attName=attributes.getQName(i);
String attValue=attributes.getValue(attName);
System.out.println(" "+attName+"='"+attValue+"'");
}
System.out.println(">");
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
//charracter方法输出文本 换行 空格
String str=new String(ch,start,length);
System.out.print(str);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("</"+qName+">");
}
}