<?xml version="1.0" encoding="UTF-8"?> <catalog> <!--An XML Catalog--> <?target instruction?> <journal title="XML Zone" publisher="IBM developerWorks"> <article level="Intermediate" date="December-2001"> <title>Java configuration with XML Schema</title> <author> <firstname>Marcello</firstname> <lastname>Vitaletti</lastname> </author> </article> </journal> </catalog>articleというノードのlevel属性を取得したい場合はselectNodes("//article/@level")とします。
package jp.co.confrage; import java.io.File; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Test005 { public static void main(String[] args) { SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(new File("C:\\a001.xml")); List list = document.selectNodes("//article/@level"); Iterator iter=list.iterator(); while(iter.hasNext()){ Attribute attribute=(Attribute)iter.next(); if(attribute.getValue().equals("Intermediate")){ attribute.setValue("test"); // testに書き換える } } list.clear(); list = document.selectNodes("//article/author"); Iterator iter2=list.iterator(); while(iter2.hasNext()){ Element element=(Element)iter2.next(); Iterator iterator=element.elementIterator("firstname"); while(iterator.hasNext()){ Element firstNameElement=(Element)iterator.next(); if(firstNameElement.getText().equals("Marcello")){ System.out.println(firstNameElement.getText()); firstNameElement.setText("test"); //testに書き換える } } } } catch (DocumentException e) { e.printStackTrace(); } } }