我有一个像这样的 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
method... 仅有的Document
有它。但我做不到docsDoc.getElementsByTagName("aoo")
,因为它会归还我全部<aoo>
节点,而不仅仅是存在于<document>
我正在检查的节点。
我怎样才能做到呢?谢谢!
If the Node
不仅仅是任何节点,而且实际上是一个Element
(它也可以是例如属性或文本节点),您可以将其转换为Element
并使用getElementsByTagName
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)