在jdom的api中提供的setAttribute(Attribute attribute)这个方法来为元素设置属性,但是我们使用的时候要注意:
a.xml文档如下:
- <?xml version="1.0" encoding="utf-8"?>
- <root>
- <ele id="1">aaa </ele>
- <ele id="2">bbb</ele>
- </root>
b.xml文档如下:
- <?xml version="1.0" encoding="utf-8"?>
- <root>
- <ele name="name1">zhangsan </ele>
- <ele name="name2">lisi</ele>
- </root>
现在我要将b文档的第一个ele节点的name属性添加到a文档的第一个ele节点的上
使用jdom工具,其代码如下
- SAXBuilder sb = new SAXBuilder();
- Document a_doc = sb.build("a.xml");
- Document b_doc = sb.build("b.xml");
- Elment a_root = a_doc.getRootElement();//得到a.xml的根节点
- Elment b_root = d_doc.getRootElement();//得到a.xml的根节点
- Element a_ ele = a_root.getChild("ele");//得到a.xml文档第一个ele节点
- Element b_ele = b_root.getChild("ele");//得到b.xml文档第一个ele节点
- Attribute att = b_ele.getAttribute("name");//得到name属性对象
//注意:
如果我们我们直接写:
- a_ele.setAttribute(att);
就会报错。错误是:The attribute already has an existing parent "ele"
正确的写法应该是:
- a_ele.setAttribute(att.getName(),att.getValue());
或者写:
- Element at = new Element(att.getName(),att.getValue());
- a_ele.setAttribute(at);