1.SAX事件解析
package com.wzh.sax; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; // public class Saxhandler extends DefaultHandler { @Override public void startDocument() throws SAXException { System.out.println("開始解析XML文檔..."); } @Override public void endDocument() throws SAXException { System.out.println("結束解析XML文檔..."); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub super.startElement(uri, localName, qName, attributes); System.out.println("開始解析節點["+qName+"]..."); System.out.println("共有["+attributes.getLength()+"]個屬性"); } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub super.characters(ch, start, length); String content =new String(ch,start,length); System.out.println(content); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, qName); System.out.println("結束解析XML節點..."); } }
2.Dom加載解析
package com.wzh.dom; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DomHandler { /* * 解析XML */ public void read(String fileName) throws Exception { // 定義工廠API 使應用程序能夠從XML文檔獲取生成DOM對象樹的解析器 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 獲取此類的實例之后,將可以從各種輸入源解析XML DocumentBuilder builder = factory.newDocumentBuilder(); // builder.parse(this.getClass().getResourceAsStream("/" + fileName)); // Document接口表示整個HTML或XML文檔,從概念上講,它是文檔樹的根,並提供對文檔數據的基本訪問 Document document = builder.parse(this.getClass().getResourceAsStream( "/" + fileName)); // 獲取根節點 Element root = document.getDocumentElement(); System.out.println(root.getNodeName()); //讀取database節點NodeList接口提供對節點的有序集合的抽象 NodeList nodeList = root.getElementsByTagName("database"); for (int i = 0; i < nodeList.getLength(); i++) { // 獲取一個節點 Node node = nodeList.item(i); // 獲取該節點所有屬性 NamedNodeMap attributes = node.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); System.out.println(attribute.getNodeName() + ":" + attribute.getNodeValue()); } //獲取所有子節點數據 NodeList childNodes=node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node childNode=childNodes.item(j); System.out.println(childNode.getNodeName()+":"+childNode.getNodeValue()); } } } public static void main(String[] args) throws Exception { new DomHandler().read("data-source.xml"); } }
3.dom4j解析
package com.wzh.dom4j;
import java.io.FileOutputStream;
import java.sql.DatabaseMetaData;
import java.util.Iterator;
import java.util.List;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jHandler {
public void add() throws Exception {
// 1.創建一個Document
Document document = DocumentHelper.createDocument();
// 2.給Document添加數據
Element root = document.addElement("DataSource");
// 添加注釋
root.addComment("這是注釋信息");
// 在root根節點下面添加一個子節點
Element database = root.addElement("database");
database.addAttribute("name", "mysql");
database.addAttribute("version", "5.0");
// 添加子節點
database.addElement("driver").setText("com.mysql.jdbc.Driver");
database.addElement("url")
.setText("jdbc:mysql://localhost:3306/myjdbc");
database.addElement("user").setText("root");
database.addElement("password").setText("root");
// 3.將Document寫出文件
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
// FileOutputStream默認生成的路徑在根路徑
XMLWriter xw = new XMLWriter(new FileOutputStream("db.xml"), format);
xw.write(document);
xw.close();
}
public void update(String fileName) throws Exception {
// sax解析器
SAXReader saxReader = new SAXReader();
// 讀到對象
Document document = saxReader.read(this.getClass().getResourceAsStream(
"/" + fileName));
Element root = document.getRootElement();
List<Element> databases_node = root.elements("database");
for (Element database_node : databases_node) {
if (database_node.attributeValue("name").equalsIgnoreCase("mysql")) {
System.out.println("old:"
+ database_node.attributeValue("name"));
database_node.attribute("name").setText("Oracle");
System.out.println("update:"
+ database_node.attributeValue("name"));
database_node.element("driver").setText("oracel");
database_node.element("url").setText("jdbc");
// 刪除password節點
database_node.remove(database_node.element("password"));
// 刪除屬性
database_node.remove(database_node.attribute("version"));
}
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
// FileOutputStream默認生成的路徑在根路徑
XMLWriter xw = new XMLWriter(new FileOutputStream("db2.xml"), format);
xw.write(document);
xw.close();
}
public void read(String fileName) throws Exception {
// sax解析器
SAXReader saxReader = new SAXReader();
// 讀到對象
Document document = saxReader.read(this.getClass().getResourceAsStream(
"/" + fileName));
Element root = document.getRootElement();
System.out.println("根節點:" + root.getName());
// List<Element> childElements=root.elements();
List<Element> childElements = root.elements("database");
for (Element child : childElements) {
// 獲取屬性 不知道屬性名稱時的遍歷方法
List<Attribute> attributes = child.attributes();
// for (Attribute attribute : attributes) {
// System.out.println(attribute.getName()+":"+attribute.getValue());
// }
String name = child.attributeValue("name");
// String version = child.attributeValue("version");
String version = child.attribute("version").getValue();
System.out.println(name + ":" + version);
// //獲取子節點
// List<Element> childs=child.elements();
// for (Element element : childs) {
// System.out.println(element.getName()+":"+element.getText());
// }
System.out.println(child.elementText("driver"));
System.out.println(child.element("url").getText());
System.out.println(child.elementTextTrim("user"));
System.out.println(child.element("password").getTextTrim());
}
}
public static void main(String[] args) throws Exception {
// new Dom4jHandler().read("data-source.xml");
// new Dom4jHandler().add();
new Dom4jHandler().update("data-source.xml");
}
}