Jdom:Opensource,free
Commons_Configuration:Apache公司的
W3Cdom:已经被收录到java名下,在org.w3c.dom包中。
books.xml
jdom解析:
w3cDOM 解析
Commons_Configuration解析
Commons_Configuration api:http://commons.apache.org/configuration/apidocs/index.html
jdom API:见附件
Commons_Configuration:Apache公司的
W3Cdom:已经被收录到java名下,在org.w3c.dom包中。
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="B02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="B03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="B04">
<name>a</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
jdom解析:
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;
//下面是引用到JDOM中的类
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
public class testJdom {
public static void main(String[] args) {
try {
/*******************************************************************
* 解析books.xml
*/
String xPath = "./src/books.xml";
// SAXBuilder负责从文件、流、URL等来构建一个JDOM document
SAXBuilder builder = new SAXBuilder(false);
Document doc = builder.build(xPath);
Element books = doc.getRootElement();
// 设置输出到控制台
PrintStream pr = System.out;
Format format = Format.getCompactFormat(); // 创建输出格式
format.setEncoding("GBK"); // 编码
format.setIndent(" ");
XMLOutputter out = new XMLOutputter(format);
// --- 新建一个元素 ----
System.out.println("++++++++++++新增一本书开始++++++++++++");
Element theBook = new Element("book");
Element theElem = new Element("name");
theElem.setText("新加的书名");
Element thePrice = new Element("price");
// 增加一个属性
thePrice.setAttribute("incread", "yes");
thePrice.setText("50");
theBook.addContent(theElem);
theBook.addContent(thePrice);
books.addContent(theBook);
out.output(doc, pr);
System.out.println(out.toString());
System.out.println("++++++++++++新增一本书结束++++++++++++");
System.out.println("+++++++++++条件查询 ++++++++++++");
// --- 多个条件查询---
// 选取books下的所有book元素
List find1 = XPath.selectNodes(books, "/books/book");
// 选取books下的所有book的子元素price>10的元素
List find2 = XPath.selectNodes(books, "/books/book[price=10]");
// 这里的查询不支持中文??????
List find3 = XPath.selectNodes(books, "/books/book[name='a']");
// 打印出是价钱是六块钱的书名
String book1 = ((Text) XPath.selectSingleNode(books,
"/books/book[price=6]/name/text()")).getTextNormalize();
System.out.println(book1);
// 选取所有 books 元素的 book 元素,且其中的 book 元素拥有名为 id 的属性。
List find4 = XPath.selectNodes(books, "/books/book[@id]");
// 选取所有 books 元素的 book 元素,且其中的 book 元素的id属性值须等于B02。
List find5 = XPath.selectNodes(books, "/books/book[@id='B02']");
// System.out.println("find.size" + find5.size() + "--");
// Element findelement = (Element) find5.get(0);
// out.output(findelement, pr);
System.out.println("查询结束");
System.out.println("+++++++++++删除、修改元素及属性(删除B02 三国演义) ++++++++++");
Element eleB02 = (Element) XPath.selectSingleNode(books,
"/books/book[@id='B02']");
// 下面这条语句会把books中的所有子元素删除,添加此文本元素节点
// --- books.setText("dfdfdfd");
// 添加此文本元素节点
// ---books.addContent("dfdfdfd");
// 删除元素的第一种方法,先找到元素
// --books.removeContent(eleB02);
// 修改元素的属性
eleB02.setAttribute("name", "三国演****义");
//删除一个元素的属性
//--eleB02.removeAttribute("属性名");
out.output(books, pr);
// 将文件写回到XML文件
// out.output(doc,new FileOutputStream(xPath));
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
w3cDOM 解析
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
public class testDom {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Element theBook = null, theElem = null, root = null;
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document xmldoc = db.parse(new File("./src/books.xml"));
root = xmldoc.getDocumentElement();
// --- 新建一本书开始 ----
theBook = xmldoc.createElement("book");
theElem = xmldoc.createElement("name");
theElem.setTextContent("新书");
theBook.appendChild(theElem);
theElem = xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);
theElem = xmldoc.createElement("memo");
theElem.setTextContent("新书的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- 新建一本书开始 ----");
output(xmldoc);
System.out.println("--- 新建一本书完成 ----");
// --- 新建一本书完成 ----
// --- 下面对《哈里波特》做一些修改。 ----
// --- 查询找《哈里波特》----
theBook = (Element) selectSingleNode("/books/book[name='哈里波特']",
root);
System.out.println("--- 查询找《哈里波特》 ----");
output(theBook);
// --- 此时修改这本书的价格 -----
theBook.getElementsByTagName("price").item(0).setTextContent("15");// getElementsByTagName返回的是NodeList,所以要跟上item(0)
System.out.println("--- 此时修改这本书的价格 ----");
output(theBook);
// --- 另外还想加一个属性id,值为B01 ----
theBook.setAttribute("id", "B01");
System.out.println("--- 另外还想加一个属性id,值为B01 ----");
output(theBook);
// --- 对《哈里波特》修改完成。 ----
// --- 要用id属性删除《三国演义》这本书 ----
theBook = (Element) selectSingleNode("/books/book[@id='B02']",
root);
System.out.println("--- 要用id属性删除《三国演义》这本书 ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- 删除后的XML ----");
output(xmldoc);
// --- 再将所有价格低于10的书删除 ----
NodeList someBooks = selectNodes("/books/book[price<10]", root);
System.out.println("--- 再将所有价格低于10的书删除 ---");
System.out.println("--- 符合条件的书有 " + someBooks.getLength()
+ "本。 ---");
for (int i = 0; i < someBooks.getLength(); i++) {
someBooks.item(i).getParentNode()
.removeChild(someBooks.item(i));
}
output(xmldoc);
saveXml("Test1_Edited.xml", xmldoc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void output(Node node) {// 将node的XML字符串输出到控制台
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "gb2312");
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(node);
StreamResult result = new StreamResult();
result.setOutputStream(System.out);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static Node selectSingleNode(String express, Object source) {// 查找节点,并返回第一个符合条件节点
Node result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (Node) xpath
.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
public static NodeList selectNodes(String express, Object source) {// 查找节点,返回符合条件的节点集。
NodeList result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (NodeList) xpath.evaluate(express, source,
XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
public static void saveXml(String fileName, Document doc) {// 将Document输出到文件
TransformerFactory transFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
DOMSource source = new DOMSource();
source.setNode(doc);
StreamResult result = new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Commons_Configuration解析
package test;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
public class testCommonsConfiguration {
public static void main(String args[]) {
try {
String file = "./src/books.xml";
XMLConfiguration config = new XMLConfiguration(file);
System.out.println("成功加载:" + file);
String btime = config.getString("book.name");
System.out.println("书名:" + btime);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Commons_Configuration api:http://commons.apache.org/configuration/apidocs/index.html
jdom API:见附件