我正在尝试解析从HttpPost到服务器( last.fm )的last.fm安卓应用程序的XML。如果我简单地将它解析为字符串,我可以看到它是一个普通的xml字符串,其中包含所有需要的信息。但我就是不能解析单个NameValuePairs。这是我的HttpResponse对象:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();我尝试了两种不同的方法,但都不起作用。首先,我尝试检索NameValuePairs:
List<NameValuePair> answer = URLEncodedUtils.parse(r_entity);
String name = "empty";
String playcount = "empty";
for (int i = 0; i < answer.size(); i++){
if (answer.get(i).getName().equals("name")){
name = answer.get(i).getValue();
} else if (answer.get(i).getName().equals("playcount")){
playcount = answer.get(i).getValue();
}
}在此代码之后,name和playcount保持为“空”。因此,我尝试使用XML解析器:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document answer = db.parse(new DataInputStream(r_entity.getContent()));
NodeList nl = answer.getElementsByTagName("playcount");
String playcount = "empty";
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
Node fc = n.getFirstChild();
playcount Url = fc.getNodeValue();
}这似乎失败得更早,因为它甚至没有设置playcount变量。但就像我说的,如果我这样做:
EntityUtils.toString(r_entity);我将得到一个完美的xml字符串。因此,解析它应该没有问题,因为HttpResponse包含正确的信息。我做错了什么?
发布于 2011-02-12 06:52:25
我解决了。DOM XML解析器需要更多的调整:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);
String playcount = "empty";
NodeList nl = doc.getElementsByTagName("playcount");
for(int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
playcount = nameElement.getFirstChild().getNodeValue().trim();
}
}发布于 2011-02-12 06:15:39
这是一个从提要中解析XML的非常好的tutorial。您可以使用它来构建更健壮的应用程序,这些应用程序需要解析XML提要,我希望它能有所帮助
发布于 2011-02-12 06:17:02
if (answer.get(i).getName() == "name"){
不能使用==比较字符串
当我们使用==操作符时,我们实际上是在比较两个对象引用,看看它们是否指向同一个对象。例如,我们不能使用==运算符比较两个字符串是否相等。相反,我们必须使用.equals方法,它是所有类从java.lang.Object继承的方法。
下面是比较两个字符串的正确方法。
String abc = "abc"; String def = "def";
// Bad way
if ( (abc + def) == "abcdef" )
{
......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
.....
}摘自Top Ten Errors Java Programmers Make
https://stackoverflow.com/questions/4974591
复制相似问题