读书人

java中利用dom4j对XML文档的创办、解析

发布时间: 2012-09-24 13:49:41 作者: rapoo

java中利用dom4j对XML文档的创建、解析、查找、修改、保存等操作

java中利用dom4j对XML文档的创建、解析、查找、修改、保存等操作。

??
??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);
??Document doc = reader.read(new File(xmlFile));
??
??return doc;??
?}
?
?/**
??* 查找 xml
??* @param doc
??* @throws IOException
??*/

?public void listDocument(Document doc) throws IOException{
??
??String xpath = "/class/company/person[@id="11"]";
??Element list =??(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查找元素,然后修改
??* @param doc
??* @throws IOException
??*/
?public void updateDocByXPATH(Document doc) throws IOException{
??String xpath = "/class/company/person[@id="11"]";
??Element list =??(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("163@163.com");
??list.element("QQ").setText("12345");
//??}
??saveDocument(doc);

?}

?/**
??* 从根节点遍历,来修改XML文件,并保存。
??* @param doc
??* @throws IOException
??*/
?public void updateDocument(Document doc) throws IOException{
?
??Element root = doc.getRootElement();
//??System.out.println(root.asXML());
??
??for (Iterator i = root.elementIterator(); i.hasNext();) {
???Element e = (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);??
?}
?
}?

读书人网 >XML SOAP

热点推荐