DEMO1:结合XPath使用dom4j
注意要使用XPath必须要有jaxen-1.1-beta-6.jar 这个包的支持!要不然就报错!
XML的数据如下:
0.8
1234
12
修改的标签元素值0.8
代码如下:
public void modifyDocumet(File inputxml) {
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputxml);
List list = document.selectNodes("//sysinfo" );
Iterator iter=list.iterator();
while(iter.hasNext()){
Element element=(Element)iter.next();
Iterator iterator=element.elementIterator("cpu");
while(iterator.hasNext()){
Element titleElement=(Element)iterator.next();
titleElement.setText("8.58");
System.out.println(titleElement.getText());
}
}
//将doc中的内容写入文件中
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter writer= new XMLWriter(new FileWriter(inputxml),format);
writer.write(document);
writer.flush();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
}
调用:
File file = new File("c:/catalog/catalog.xml");
new XMLUtils().modifyDocumet(file);
DEMO2、XML的格式如下:
8.58
1234
12
15
200
解析的代码:
public void modifyDocument(File inputxml, String rootNode, String nodeName,String value) {
try{
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputxml);
List list = document.selectNodes("root/" + rootNode);
Iterator iter = list.iterator();
while (iter.hasNext()) {
Element element = (Element)iter.next();
Iterator iterator= element.elementIterator(nodeName);
Element currElement = (Element)iterator.next();
currElement.setText(value);
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter writer= new XMLWriter(new FileWriter(inputxml),format);
writer.write(document);
writer.flush();
}catch (Exception e) {
System.out.println(e.toString());
}
}
如果是三级一样的可以递增进来的!
以上是修改元素值当然也可以修改元素的属性。也通过XPath方法操作 的!
整理如下:
DEMO3:修改元素的属性值
XML文件格式如下:
阅读(1091) | 评论(0) | 转发(0) |