java中利用dom4j对XML文档的创建、解析、查找、修改、保存等操作
java中利用dom4j对XML文档的创建、解析、查找、修改、保存等操作。
前两天,在java项目中写了一些关于对XML文档的操作,利用dom4j对XML文档的创建、解析、查找、修改、保存,校验等操作。以下代码供有需要的朋友参考。
import java.io.File;
import java.io.FileNotFoundException;import java.io.FileOutputStream;
import java.io.IOException;
importjava.io.OutputStreamWriter;
import java.util.Iterator;import org.dom4j.Document;
importorg.dom4j.DocumentException;
importorg.dom4j.DocumentHelper;
import org.dom4j.Element;import org.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
importorg.dom4j.io.XMLWriter;
importorg.xml.sax.SAXException;
/***
*JDK版本:jdk5.0
*利用dom4j对XML文档的创建、解析、查找、修改、保存等操作。
*@authorJackChen
*日期:2007-05-17
*/
public class TestXML {public static final String SAVE_XMLFILE_PATH = "saveXML.xml";
public TestXML() {
}
/**
*创建一个XML文档
*@returndoc返回该文档
*/
publicDocumentcreateXMLDocument(){
Documentdoc=null;
doc=DocumentHelper.createDocument();
doc.addComment("editedwithXMLSpyv2005rel.3U(http://www.altova.com)by()");
//doc.addDocType("class","//ByJackChen","saveXML.xsd");
Elementroot=doc.addElement("class");
Elementcompany=root.addElement("company");
Elementperson=company.addElement("person");
person.addAttribute("id","11");
person.addElement("name").setText("JackChen");
person.addElement("sex").setText("男");
person.addElement("date").setText("2001-04-01");
person.addElement("email").setText("[email protected]");
person.addElement("QQ").setText("2366001");return doc;
}
/**
*解析XML文档
*@paramxmlFile
*@returnXML文档
*@throwsDocumentException
*@throwsFileNotFoundException
*/
publicDocumentparse(StringxmlFile)throwsDocumentException,FileNotFoundException{
SAXReaderreader=newSAXReader();
Documentdoc=reader.read(newFile(xmlFile));
returndoc;
}
/***
*将XML文档输出到控制台
*@paramdoc
*@throwsIOException
*/
publicvoidprintDocument(Documentdoc)throwsIOException{
OutputFormatformat=OutputFormat.createPrettyPrint();
XMLWriterwriter=newXMLWriter(newOutputStreamWriter(System.out),format);
writer.write(doc);
writer.close();
}/**
*保存XML文档
*@paramdoc
*@throwsIOException
*/
publicvoidsaveDocument(Documentdoc)throwsIOException{
OutputFormatformat=OutputFormat.createPrettyPrint();
XMLWriterwriter=newXMLWriter(newFileOutputStream(SAVE_XMLFILE_PATH),format);
writer.write(doc);
writer.close();
}
/**
*验证XML文档和schemaURL
*@paramxmlFile
*@paramschemaUrl
*@returnXML文档
*@throwsSAXException
*@throwsDocumentException
*/
publicDocumentvalidate(StringxmlFile,StringschemaUrl)throwsSAXException,DocumentException{
SAXReaderreader=newSAXReader(true);
System.out.println("validateby:"+schemaUrl);
reader.setFeature("http://apache.org/xml/features/validation/schema",true);
reader.setFeature("http://xml.org/sax/features/validation",true);
reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
schemaUrl);
reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking",
true);
Documentdoc=reader.read(newFile(xmlFile));
returndoc;
}
/**
*查找xml
*@paramdoc
*@throwsIOException
*/public void listDocument(Document doc) throws IOException{
Stringxpath="/class/company/person[@id="11"]";
Elementlist=(Element)doc.selectSingleNode(xpath);
System.out.println(list.getName());// if (list.element("name").getName().equals("name")) {
System.out.println("name:"+list.element("name").getText());
System.out.println("sex:"+list.element("sex").getText());
System.out.println("date:"+list.element("date").getText());
System.out.println("email:"+list.element("email").getText());
System.out.println("QQ:"+list.element("QQ").getText());
}
/***
*利用XPATH查找元素,然后修改
*@paramdoc
*@throwsIOException
*/
publicvoidupdateDocByXPATH(Documentdoc)throwsIOException{
Stringxpath="/class/company/person[@id="11"]";
Elementlist=(Element)doc.selectSingleNode(xpath);
System.out.println(list.getName());// if (list.element("name").getName().equals("name")) {
list.element("name").setText("1123");
list.element("sex").setText("男");
list.element("date").setText("1800-01-01");
list.element("email").setText("[email protected]");
list.element("QQ").setText("12345");
//}
saveDocument(doc);}
/**
*从根节点遍历,来修改XML文件,并保存。
*@paramdoc
*@throwsIOException
*/
publicvoidupdateDocument(Documentdoc)throwsIOException{
Elementroot=doc.getRootElement();
//System.out.println(root.asXML());
for(Iteratori=root.elementIterator();i.hasNext();){
Elemente=(Element)i.next();
System.out.println(e.getName());
System.out.println(e.getPath());
if(e.element("person").element("name").getName().equals("name")){
e.element("person").element("name").setText("ChenJI");
e.element("person").element("QQ").setText("123456");}
System.out.println(e.getText().toString());
}
saveDocument(doc);
}
}