利用xpath修改节点(值)内容

public static void modifyXMLFile() {

String oldStr = "c:/text.xml";

String newStr = "c:/text1.xml";

Document document = null;

//修改节点的属性

try {

SAXReader saxReader = new SAXReader(); // 用来读取xml文档

document = saxReader.read(new File(oldStr)); // 读取xml文档

List list = document.selectNodes("/books/book/@show");// 用xpath查找节点book的属性

Iterator iter = list.iterator();

while (iter.hasNext()) {

Attribute attribute = (Attribute) iter.next();

if (attribute.getValue().equals("yes"))

    attribute.setValue("no");

}

} catch (Exception e) {

    e.printStackTrace();

}

//修改节点的内容

try {

SAXReader saxReader = new SAXReader(); // 用来读取xml文档

document = saxReader.read(new File(oldStr)); // 读取xml文档

List list = document.selectNodes("/books/book/title");// 用xpath查找节点book的内容

Iterator iter = list.iterator();

while (iter.hasNext()) {

Element element = (Element) iter.next();

element.setText("xxx");// 设置相应的内容

}

} catch (Exception e) {

    e.printStackTrace();

}



try {

XMLWriter writer = new XMLWriter(new FileWriter(new File(newStr)));

writer.write(document);

writer.close();

} catch (Exception ex) {

    ex.printStackTrace();

}

}





http://www.cnblogs.com/forlina/archive/2011/06/09/2076534.html

你可能感兴趣的:(java,xml,dom4j,xpath)