假设我有一个XML文件:
<catalog>
<book>
<isbn>1</isbn>
<author> A</author>
<title>Title A</title>
<description> Desc A</description>
</book>
<book>
<isbn>2</isbn>
<author>B</author>
<title>Title B</title>
<description>Desc B</description>
</book>
...
<catalog>
根据Android documentation,我可以像这样获取我的Activity中的所有数据:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
stringXmlContent = getEventsFromAnXML(this);
...
}
private String getEventsFromAnXML(Activity activity)
throws XmlPullParserException, IOException {
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.myxmlfile );
xpp.next();
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
stringBuffer.append("\nSTART_TAG: " + xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
stringBuffer.append("\nEND_TAG: " + xpp.getName());
} else if (eventType == XmlPullParser.TEXT) {
stringBuffer.append("\nTEXT: " + xpp.getText());
}
eventType = xpp.next();
}
return stringBuffer.toString();
}
虽然这会从XML文件中获取所有内容,但我真的很难在特定条件下过滤掉它。
例如,让我们说我想获得isbn为2的书的作者名称。如何使用pullparser过滤掉这些数据?
答案 0 :(得分:1)
检查并根据您的需要进行修改
URL url2 = new URL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" +artist+ "&api_key=1732077d6772048ccc671c754061cb18");
URLConnection connection = url2.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(30000);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
final Document document = db.parse(connection.getInputStream());
document.getDocumentElement().normalize();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xPathEvaluator = xPathfactory.newXPath();
XPathExpression nameExpr = xPathEvaluator.compile("//lfm/artist/image");
// XPathExpression nameExpr = xPathEvaluator.compile("//lfm/tracks/track/image");
NodeList nl = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);
for (int zzz = 0; zzz < nl.getLength(); zzz++)
{
Node currentItem = nl.item(zzz);
key = currentItem.getTextContent();
// key = currentItem.getAttributes().getNamedItem("uri").getNodeValue();
}
在变量键中,我得到包含图像的节点的值
答案 1 :(得分:1)
它需要一些猜测和检查(至少这是我在做的时候所需要的),但你可以轻松测试某个节点的文本,看看ISBN是否为2(如果是,你可以继续解析数据。否则,你可以继续前进,直到你到达下一个ISBN节点。