需求描述:需要把xml文档中的div(有节点或者有值)的节点名字修改为span,且要把其中的x,y属性名称改成left , top 。 `
try {
SAXReader saxReader = new SAXReader();
Document dom = saxReader.read(new File("replaceDemo.xml"));
Element root = dom.getRootElement();
Iterator<Element> controls = root.elementIterator("Control") ;
while(controls.hasNext()){
Element control = controls.next();
if(control.hasContent()){ //条件过滤 那些节点需要修改
control.setName("span"); //修改节点的名称
//start 对节点中属性修改 无法直接修改属性名称 只能先删除 在添加
Attribute xattribute = control.attribute("x");
Attribute yattribute = control.attribute("y");
control.addAttribute("left",xattribute.getValue());
control.addAttribute("top",yattribute.getValue());
control.remove(xattribute);
control.remove(yattribute);
}
}
//输出到文件中
FileOutputStream fileOutputStream = new FileOutputStream("replaced.xml");
fileOutputStream.write(dom.asXML().getBytes("UTF-8"));
fileOutputStream.close();
} catch (MalformedURLException e){
e.printStackTrace();
} catch (DocumentException e){
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
`