xml解析分为四种分别为:
1.DOM解析;
2.SAX解析;
3.DOM4J解析;
4.JDOM解析;
我讲解DOM4J解析:
DOM4J特征:
1.JDOM的一种智能分支,它合并了许多超出基本XML文档表示的功能;
2.使用接口和抽象类方法;
3.具有性能优异、灵活性好、功能强大和极端易用的特点;
4.是一个开放源码的文件。
第一步:
导包
第二步:
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Demo01 {
public static void main(String[] args) {
InputStream is=Demo01.class.getResourceAsStream("/test /db.properties");
System.out.println(is);
Properties pp= new Properties();
try {
pp.load(is);
String name=pp.getProperty("user");
String password =pp.getProperty("password");
System.out.println(name+"="+password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student sid="s001">
<name>小明</name>
</student>
<student sid="s002">
<name>小芳</name>
</student>
<student sid='y003s'>
<name>小王</name>
</student>
<student sid='w004' qq="111">
<name>小李</name>
</student>
</students>
package test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Demo02 {
public static void main(String[] args) {
InputStream is=Demo02.class.getResourceAsStream("/test/students.xml");
System.out.println(is);
SAXReader sr= new SAXReader();
try {
Document doc=sr.read(is);
List<Node> studentNodes =doc.selectNodes("/students/student");
System.out.println(studentNodes.size());
// List nameNodes =doc.selectNodes("/students/student/name");
// System.out.println(nameNodes.size());
for (Node node : studentNodes) {
Node nameNode=node.selectSingleNode("name");
String name=nameNode.getText();
System.out.println(name);
Element el= (Element)node ;
String sid=el.attributeValue("sid");
System.out.println(sid);
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
}