状況
dom4jを使用して、XMLファイルを加工しています。
W3Cでなく、dom4jを使用しているのは、xPathを使用する必要があるためです。
しかし、dom4jではメソッドが十分ではありません。
素人なりに調べたところ、dom4j.dom のDOMElementで上記を実現できる気がしている
のですが、DOMElementの実装の仕方が全くわかりません。
以下のコードをDOMElementを用いて書き直したいのですが、どうしたらよいでしょうか。
そもそも検討違いなことをいっているかもしれませんが、そうであればご指摘ください。
コード
import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class Sampe1 { public static void main(String[] args) { SAXReader reader = new SAXReader(); try { Document document = reader.read("catalog.xml"); List books =document.selectNodes("catalog/book"); for(Iterator i = books.iterator(); i.hasNext();){ Node book = (Node)i.next(); List aList = book.selectNodes("./a"); for(Iterator i2 = aList.iterator(); i2.hasNext();){ Node aNode = (Node)i2.next(); int aInt = Integer.parseInt( aNode.valueOf("./@volume")); //以下一文、getNextSiblingで書き換えたい。 Node NextSiblingNode= aNode.selectSingleNode("./following-sibling::*"); int nextInt = Integer.parseInt(NextSiblingNode.valueOf("./@volume")); // //以下 DOMElementのhasAttributeを使って以下のことをしたい。このままではエラー // if(aNode.hasAttribute("volume");){ // if(NextSiblingNode.hasAttribute("volume")){ // if(aInt > nextInt){ // System.out.println(aInt+"is larger than"+ nextInt); // } // } // } }
読み込んだXML(catalog.xml)
<catalog> <book> <a num = "1" volume = "10">Gambardella, Matthew</a> <a num = "2" volume = "7">XML Developer's Guide</a> <a num = "3" volume = "3">Computer</a> <a num = "4">44.95</a> <a num = "5">2000-10-01</a> <a num = "6">An in-depth look at creating applications with XML.</a> </book> <book> <a num = "3" volume = "3">Fantasy</a> <a num ="4" >5.95</a> <a num = "5">2000-12-16</a> <a num = "6">A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</a> </book> <book> <a num = "4">5.95</a> <a num = "5">2000-11-17</a> <a num = "6">After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</a> </book> </catalog>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。