如何使用java从xml文件中提取细节?

我有以下类型的XML文件,

    224589801 NC_000010 Homo sapiens chromosome 10, GRCh37.p10 Primary Assembly gi|224589801|gnl|ASM:GCF_000001305|10|ref|NC_000010.10||gpp|GPC_000000034.1||gnl|NCBI_GENOMES|10[224589801] 224589801 2002/08/29 2012/10/30 544 9606 135534747 live     

如何从node =“Item”中提取细节,具体取决于它的名称值? 使用标准的java dom xml或者更好地使用任何其他xml解析器库是为了这个目的吗?

我建议使用StAX,试试这个(javax.xml.stream。*)

  XMLInputFactory f = XMLInputFactory.newInstance(); XMLStreamReader rdr = f.createXMLStreamReader(new FileReader("test.xml")); while (rdr.hasNext()) { if (rdr.next() == XMLStreamConstants.START_ELEMENT) { if (rdr.getLocalName().equals("Item")) { System.out.println(rdr.getAttributeValue("", "Name")); System.out.println(rdr.getElementText()); } } } 

StAX必须始终是首要考虑因素。 请参阅http://en.wikipedia.org/wiki/StAX,您将了解原因

请尝试以下代码

 /* Create a Document object (doc) from the xml */ NodeList list = doc.getElementsByTagName("Item"); for(int i=0;i 

输出应为NC_000010

如果只使用标准Java,XPath是要走的路:

 private URL xml = getClass().getResource("/example.xml"); @Test public void testExamples() throws Exception { //assertEquals("NC_000010", extractUsingDom("Caption")); assertEquals("NC_000010", extractUsingXPath("Caption")); } public String extractUsingXPath(final String name) throws XPathExpressionException, IOException { // XPathFactory class is not thread-safe so we do not store it XPath xpath = XPathFactory.newInstance().newXPath(); return xpath.evaluate( String.format("/eSummaryResult/DocSum/Item[@Name='%s']", name), // xpath expression new InputSource(xml.openStream())); // the XML Document } 

也许使用XPath?

 Document dom = ...; XPath xpath = XPathFactory.newInstance().newXPath(); String result = xpath.evaluate("/eSummaryResult/DocSum/Item[@Name='Title']", dom);