java操作dom节点的添加_java Dom节点名称和属性名的修改

需求描述:需要把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 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();

}

`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值