jdom中使用setAttribute(Attribute attribute)方法设置属性的注意事项

 在jdom的api中提供的setAttribute(Attribute attribute)这个方法来为元素设置属性,但是我们使用的时候要注意:

a.xml文档如下:

 

 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <root>
  3.   <ele id="1">aaa </ele>
  4.   <ele id="2">bbb</ele>
  5. </root>

b.xml文档如下:

 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <root>
  3.   <ele name="name1">zhangsan </ele>
  4.   <ele name="name2">lisi</ele>
  5. </root>

现在我要将b文档的第一个ele节点的name属性添加到a文档的第一个ele节点的上

使用jdom工具,其代码如下

 

  1. SAXBuilder sb = new SAXBuilder();
  2. Document a_doc = sb.build("a.xml");
  3. Document b_doc = sb.build("b.xml");
  4. Elment a_root = a_doc.getRootElement();//得到a.xml的根节点
  5. Elment b_root = d_doc.getRootElement();//得到a.xml的根节点
  6. Element a_ ele = a_root.getChild("ele");//得到a.xml文档第一个ele节点
  7. Element b_ele =  b_root.getChild("ele");//得到b.xml文档第一个ele节点
  8. Attribute att = b_ele.getAttribute("name");//得到name属性对象

//注意:

如果我们我们直接写:

  1. a_ele.setAttribute(att);

就会报错。错误是:The attribute already has an existing parent "ele" 

正确的写法应该是:

 

  1. a_ele.setAttribute(att.getName(),att.getValue());

或者写:

  1. Element at = new Element(att.getName(),att.getValue());
  2. a_ele.setAttribute(at);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值