的元素和属性,需要jaxen的支持。
示例中将students-gen.xml的第一个student元素的sn属性改为001,其子元素name内容改为jeff。
XmlMod.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlMod {
public void modifyDocument(File inputXml) {
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
List list = document.selectNodes("//students/student/@sn");
Iterator iter = list.iterator();
while (iter.hasNext()) {
Attribute attribute = (Attribute) iter.next();
if (attribute.getValue().equals("01"))
attribute.setValue("001");
}
list = document.selectNodes("//students/student");
iter = list.iterator();
while (iter.hasNext()) {
Element element = (Element) iter.next();
Iterator iterator = element.elementIterator("name");
while (iterator.hasNext()) {
Element nameElement = (Element) iterator.next();
if (nameElement.getText().equals("sam"))
nameElement.setText("jeff");
}
}
XMLWriter output = new XMLWriter(new FileWriter(new File(
"students-modified.xml")));
output.write(document);
output.close();
}
catch (DocumentException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] argv) {
XmlMod dom4jParser = new XmlMod();
dom4jParser.modifyDocument(new File("students-gen.xml"));
}
}
DOM4J介绍与代码示例(4)
时间:2011-07-08 51cto博客 zhangjunhd
1.使用File定位文件资源,并基于此获得Document实例
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
2.Document实例的selectNodes方法可以传入xpath,并返回一个List实例,基于此使用迭代器,完成特定的应用
List list = document.selectNodes("//students/student/@sn");
4.遍历XML文档
这里提供两种遍历方法,一种是基于迭代的遍历,一种是基于Visitor模式的遍历。
XmlTra.java
import java.io.File;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.ProcessingInstruction;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;
public class XmlTra {
private File inputXml;
public XmlTra(File inputXml) {
this.inputXml = inputXml;
}
public Document getDocument() {
SAX
|