我有一个这样的 XML:
<thoughts>
<thought>
<id>1</id>
<category>Leadership</category>
<what>sometext</what>
<who>sometext</who>
</thought>
<thought>
<id>2</id>
<category>Leadership</category>
<what>sometext</what>
<who>sometext</who>
</thought>
... 100's of with category Leadership
<thought>
<id>1</id>
<category>Love</category>
<what>sometext</what>
<who>sometext</who>
</thought>
<thought>
<id>2</id>
<category>Love</category>
<what>sometext</what>
<who>sometext</who>
</thought>
... 100's of with category Love
... and so on up to about ten categories
</thoughts>
我在 java 中解析这个 xml 以获取 android 中的特定类别和 id。这是我的代码:
String id= "100",category="Love";// for example
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(getResources().openRawResource(R.raw.thoughts));
doc.getDocumentElement().normalize();
// Log.d(LOG,"root: " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("thought");
for (int temp = 0; temp < nList.getLength(); temp++) {
org.w3c.dom.Node nNode = nList.item(temp);
Element eElement = (Element) nNode;
if (nNode.getNodeType() == Node.ELEMENT_NODE && getTagValue("id", eElement).contains(id) && getTagValue("category", eElement).contains(category)) {
Log.d("THOUGHTSERVICE", "getTagValue(\"what\", eElement):"+getTagValue("what", eElement));
what = getTagValue("what", eElement);
who = getTagValue("who", eElement);
}
}
问题是:这是一种蛮力。你能建议一些其他的方法吗?可以举个例子。
提前致谢