import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class ReadXMLByDom {
public static void main(String [] args){
ReadXMLByDom r = new ReadXMLByDom();
r.readXMLAllAttr();
r.readXMLAllElement();
r.readXMLAttr();
r.readXMLElement();
}
//第一种:根据属性来查找
//结果为:<book id="2"><Name>Linux</Name><price>100</price></book>
public void readXMLAttr() {
String str = "<books><book id='1'><Name>Java</Name><price>100</price></book>";
str = str
+ "<book id='2'><Name>Linux</Name><price>100</price></book></books>";
// 生成一个Document
Document document = null;
try {
document = DocumentHelper.parseText(str);
Element book = (Element) document
.selectSingleNode("/books/book[@id='2']");
System.out.println(book.asXML());
} catch (DocumentException e) {
e.printStackTrace();
}
}
//第二种:根据节点名来查找
//结果为:Java,Linux,
public void readXMLElement() {
String str = "<books><book id='1'><Name>Java</Name><price>100</price></book>";
str = str
+ "<book id='2'><Name>Linux</Name><price>100</price></book></books>";
Document document = null;
try {
document = DocumentHelper.parseText(str);
List names = document.selectNodes("//Name");// 记得这边是双斜杠且有区分大小写
for (int i = 0; i < names.size(); i++) {
System.out.print(((Element) names.get(i)).getText() + ",");
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
//第三种:遍历整个XML取得属于指定类型节点的记录
//结果为:1 Java 100
// 2 Linux 100
public void readXMLAllElement() {
String str = "<books><book id='1'><Name>Java</Name><price>100</price></book>";
str = str
+ "<book id='2'><Name>Linux</Name><price>100</price></book></books>";
Document document = null;
try {
document = DocumentHelper.parseText(str);
Iterator it = document.getRootElement().elementIterator();
Element element = null;
while (it.hasNext()) {
element = (Element) it.next();
if (element.getName().equals("book")) {
System.out.print(element.attributeValue("id") + " ");
System.out.print(element.element("Name").getText() + " ");
System.out.println(element.element("price").getText());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
//第四种:遍历所有属性
//结果为:id:1
// name:Java
// price:120
public void readXMLAllAttr() {
String str = "<book id='1' name='Java' price='120'/>";
Document document;
try {
document = DocumentHelper.parseText(str);
Iterator attributes = document.getRootElement().attributeIterator();
while (attributes.hasNext()) {
Attribute attribute = (Attribute) attributes.next();
System.out.println(attribute.getName() + ":"
+ attribute.getValue());
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/qking93415981/archive/2007/09/14/1785114.aspx