最好的解决方案是使用XPath。您的pastebin已过期,但这是我收集的内容。假设我们有以下
feed.xml文件:
<?xml version="1.0" encoding="UTF-8" ?><entries><entry> <title>FEED TITLE 1</title> <id>id1</id> <tempi type="type1"> <conento xmlns="dontcare?" madeIn="MadeIn1" /> </tempi></entry><entry> <title>FEED TITLE 2</title> <id>id2</id> <tempi type="type2"> <conento xmlns="dontcare?" madeIn="MadeIn2" /> </tempi></entry><entry> <id>id3</id></entry></entries>
这是一个简短但可编译且可运行的概念证明(
feed.xml文件位于同一目录中)。
import javax.xml.xpath.*;import javax.xml.parsers.*;import org.w3c.dom.*;import java.io.*;import java.util.*;public class XPathTest { static class Entry { final String title, id, origin, type; Entry(String title, String id, String origin, String type) { this.title = title; this.id = id; this.origin = origin; this.type = type; } @Override public String toString() { return String.format("%s:%s(%s)[%s]", id, title, origin, type); } } final static XPath xpath = XPathFactory.newInstance().newXPath(); static String evalString(Node context, String path) throws XPathexpressionException { return (String) xpath.evaluate(path, context, XPathConstants.STRING); } public static void main(String[] args) throws Exception { File file = new File("feed.xml"); document document = documentBuilderFactory.newInstance().newdocumentBuilder().parse(file); NodeList entriesNodeList = (NodeList) xpath.evaluate("//entry", document, XPathConstants.NODESET); List<Entry> entries = new ArrayList<Entry>(); for (int i = 0; i < entriesNodeList.getLength(); i++) { Node entryNode = entriesNodeList.item(i); entries.add(new Entry( evalString(entryNode, "title"), evalString(entryNode, "id"), evalString(entryNode, "tempi/conento/@madeIn"), evalString(entryNode, "tempi/@type") )); } for (Entry entry : entries) { System.out.println(entry); } }}这将产生以下输出:
id1:FEED TITLE 1(MadeIn1)[type1]id2:FEED TITLE 2(MadeIn2)[type2]id3:()[]
请注意,使用XPath如何使值检索变得非常简单,直观,易读和直接,并且“丢失”值也得到了很好的处理。
API链接
package javax.xml.xpath
- http://www.w3.org/TR/xpath
- 维基百科/ XPath



