获取另一个节点的子节点,给定节点名称
我有一个这样的XML:
<documentslist>
<document>
<docnumber>1</docnumber>
<docname>Declaration of Human Rights</docname>
<aoo>lib</aoo>
</document>
<document>
<docnumber>2</docnumber>
<docname>Fair trade</docname>
<aoo>lib</aoo>
</document>
<document>
<docnumber>3</docnumber>
<docname>The wars for water</docname>
<aoo>lib</aoo>
</document>
<!-- etc. -->
</documentslist>
我有这个代码:
//XML parsing
Document docsDoc = null;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
docsDoc = db.parse(new InputSource(new StringReader(xmlWithDocs)));
}
catch(ParserConfigurationException e) {e.printStackTrace();}
catch(SAXException e) {e.printStackTrace();}
catch(IOException e) {e.printStackTrace();}
//retrieve document elements
NodeList docs = docsDoc.getElementsByTagName("document");
if (docs.getLength() > 0){
//print a row for each document
for (int i=0; i<docs.getLength(); i++){
//get current document
Node doc = docs.item(i);
//print a cell for some document children
for (int j=0; j<columns.length; j++){
Node cell;
//print docname
cell = doc.getElementsByTagName("docname").item(0); //doesn't work
System.out.print(cell.getTextContent() + "\t");
//print aoo
cell = doc.getElementsByTagName("aoo").item(0); //doesn't work
System.out.print(cell.getTextContent() + "\t");
}
System.out.println();
}
}
但是,如您所知,Node
没有getElementsByTagName
方法...只有它。但是我不能这样做,因为它会返回我所有节点,而不仅仅是我正在检查的节点中存在的节点。Document
docsDoc.getElementsByTagName("aoo")
<aoo>
<document>
我该怎么做?谢谢!