我有一个这样的 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>
中存在的一个我正在检查的节点。
我该怎么做?谢谢!
最佳答案
如果 Node
不只是任何节点,而实际上是一个 Element
(也可以是属性或文本节点),您可以将其转换为 Element
并使用 getElementsByTagName
。
关于java - 获取另一个节点的子节点,给定节点名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5568262/