使用DOM(Java)解析XML文件

我想解析以下url: http : //eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi? db = nnucleotide& id = 22485891

结果我想出了以下方法:

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(),但仍无济于事。

  1. 为什么我要做n.getFirstChild().getNodeValue(); 获得实际价值? n.getNodeValue()只返回null? 这不是反直觉 – 显然在我的情况下节点没有子节点?

  2. 是否有一些更强大且被广泛接受的使用DOM解析XML文件的方法? 我的文件最多不会是15-20行,所以SAX不是必需的(或者是吗?)

 import java.io.IOException; import java.net.URL; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class XMLParser { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub parseXml2("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=nucleotide&id=224589801"); } public static 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++) { System.out.print("Item "+(i+1)); Node n = nodeList.item(i); NamedNodeMap m = n.getAttributes(); System.out.print(" Name: "+m.getNamedItem("Name").getTextContent()); System.out.print(" Type: "+m.getNamedItem("Type").getTextContent()); Node actualNode = n.getFirstChild(); if (actualNode != null) { System.out.println(" "+actualNode.getNodeValue()); } else { System.out.println(" "); } } } catch (Exception ex) { ex.printStackTrace(); } } } 

完成示例代码并添加几行以获取属性。

这应该让你开始,虽然我觉得你需要让自己了解DOM的基本概念。 该网站(以及许多其他网站)可以为您提供帮助。 最重要的是要了解不同类型的节点。

  1. 由XML标记包围的文本值也被视为DOM中的节点。 这就是为什么你必须在获得值之前得到文本节点。 如果您尝试计算的节点数,您将看到只要有文本,就会有一个节点。

  2. XOM具有更直观的界面,但它没有org.w3c.dom.*界面。

如果你想使用内置解析器,你应该查看http://www.java-samples.com/showtutorial.php?tutorialid=152

您尝试使用的DOMParser是适当的,并且它不可移植。

xml元素内的文本位于文本节点中,因为子元素可以与文本混合。 例如:

 ... blahblah ... 

元素A有三个子节点:文本节点,元素B,另一个文本节点。