【发布时间】:2014-03-18 04:01:08
【问题描述】:
我正在尝试从响应中解析 xml 流以填充我的 android 应用程序中的某些字段。如果响应中包含一个关键节点项和多个子项,我可以解析响应。
XML 是
<?xml version="1.0" encoding="UTF-8"?>
<menu>
<item>
<id>1</id>
<name>Margherita</name>
<cost>155</cost>
<description>Single cheese topping</description>
</item>
<item>
<id>2</id>
<name>Double Cheese Margherita</name>
<cost>225</cost>
<description>Loaded with Extra Cheese</description>
</item>
<item>
<id>3</id>
<name>Fresh Veggie</name>
<cost>110</cost>
<description>Oninon and Crisp capsicum</description>
</item>
<item>
<id>4</id>
<name>Peppy Paneer</name>
<cost>155</cost>
<description>Paneer, Crisp capsicum and Red pepper</description>
</item>
<item>
<id>5</id>
<name>Mexican Green Wave</name>
<cost>445</cost>
<description>Onion, Crip capsicum, Tomato with mexican herb</description>
</item>
</menu>
我的 xml 解析器在下面
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
我的解析代码是
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
String name = parser.getValue(e, KEY_NAME); // name child value
String cost = parser.getValue(e, KEY_COST); // cost child value
String description = parser.getValue(e, KEY_DESC); // description child value
}
例如,当 xml 变为多级时,我的问题就开始了
<?xml version="1.0" encoding="UTF-8"?>
<menu>
<item>
<id>1</id>
<name>Margherita</name>
<originalcost>
<cost>
<ori_cost>$30</ori_cost><tax>$.2</tax>
</cost>
</originalcost>
<description>Single cheese topping</description>
</item>
</menu>
我该如何解析上面说的例子?
【问题讨论】:
-
为什么不用xml pullparser