我想解析以下網址:http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=nucleotide&id=224589801解析XML文件
當我想出了下面的方法結果:
public void parseXml2(String URL) {
DOMParser parser = new DOMParser();
try {
parser.parse(new InputSource(new URL(URL).openStream()));
Document doc = parser.getDocument();
NodeList nodeList = doc.getElementsByTagName("Item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
Node actualNode = n.getFirstChild();
if (actualNode != null) {
System.out.println(actualNode.getNodeValue());
}
}
} catch (SAXException ex) {
Logger.getLogger(TaxMapperXml.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TaxMapperXml.class.getName()).log(Level.SEVERE, null, ex);
}
}
用這種方法我可以取值Item節點,但我不能接受它們的任何屬性。我試着用NamedNodeMap試驗getAttribute(),但仍無濟於事。
爲什麼我要做
n.getFirstChild().getNodeValue();
得到的實際價值?n.getNodeValue()
只返回null?這不是反直覺 - 顯然在我的情況下,節點的沒有子節點?是否有一些更強大和更廣泛接受的使用DOM解析XML文件的方式?我的文件都不會是最多大15-20行,所以SAX是沒有必要的(是嗎?)
您可以編寫一個簡單的助手類來完成圍繞DOM的任務。看到這個http://stackoverflow.com/a/8346867/851432 – Jomoos