我正在开发一个应用程序,在该应用程序中使用 rest webservice 从服务器获取 xml。从服务器获取响应(以 xml 格式表示)后,我使用 Dom 解析器将其解析为字符串。以下是我的 xml 响应的示例结构。
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<rating>Gloves</rating>
</brand>
<categories>
<categorie Table >
<sourseUrl Chair>
<image available="true" height="400" width="400">
<serverURL http://abcd.xyzpqr.com/images/pi/89 /da/0c=121017011508&=3>
</serverURL>
</sourseUrl>
</categorie>
<relatedProducts >
<sometag ........>
<childtag1.........> </childtag1>
<childtag2.........>
<tag1.....>
<tag2.....>
</childtag2>
</sometag>
</relatedProducts>
..........
..........
..........
</categories>
以下是我通过发出 HTTP 请求获取 XML 内容的代码
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpHost proxy = new HttpHost("45.28.19.345", 1234);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
HttpEntity httpEntity = httpResponse.getEntity();
xml = getASCIIContentFromEntity(httpEntity);</pre>
通过传递元素节点名称来获取每个 xml 子元素值 public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); 返回 this.getElementValue(n.item(0)); }
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 "";
}
这是检索已解析的 xml 数据的方式。
String newxml = xml.toString();
Document doc = parser.getDomElement(newxml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
for(int k = 0; k < doc.getChildNodes().getLength(); k++) {
Element e = (Element) nl.item(k);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);</pre>
getDomElement(String xml) 方法是
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
if(is != null){
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
通过使用此逻辑,我能够检索简单的 xml,但不能检索我上面提到的复杂 xml。有人可以给出一个想法来从嵌套的 xml 中获取数据。