转自:
Java dom4j如何获取,添加,删除,查找,设置Element属性呢?
下文讲述dom4j操作Element属性的方法分享,如下所示:
Element root=document.getRootElement(); Attribute attribute=root.attribute("size");// 属性名name
String text=attribute.getText(); // 这个是取得根节点下name字节点的属性firstname的值: String text2=root.element("name").attributeValue("firstname");
Element root=document.getRootElement(); for(Iterator it=root.attributeIterator();it.hasNext();){ Attribute attribute = (Attribute) it.next(); String text=attribute.getText(); System.out.println(text); }
newMemberElm.addAttribute("name", "属性值");
Attribute attribute=root.attribute("name"); attribute.setText("属性值");
Attribute attribute=root.attribute("name");// 属性名name root.remove(attribute);
例
public void modifyDoc() { try { Document doc = reader.read(new File("file/test.xml")); //修改属性内容 List list = doc.selectNodes("//article/@level"); Iteratoriter = list.iterator(); while (iter.hasNext()) { Attribute attr = iter.next(); fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText()); if ("Intermediate".equals(attr.getValue())) { //修改属性值 attr.setValue("新属性值"); fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText()); } } list = doc.selectNodes("//article/@date"); iter = list.iterator(); while (iter.hasNext()) { Attribute attr = iter.next(); fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText()); if ("我是属性值".equals(attr.getValue())) { //修改属性值 attr.setValue("新属性值"); fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText()); } } //写入到文件 /*XMLWriter output = new XMLWriter(new FileWriter(new File("file/test.xml"))); output.write(doc); output.close();*/ } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }