我有这个 xml 文件,并且我获得了一个NodeList
包含所有模型的文件,当我调用时myNodeList.getLength()
,它给了我正确的数字 2。但是当我调用myNodeList.item(0).getNodeValue()
应该返回的url1
时,它不显示任何值。有什么问题??
<?xml version="1.0" encoding="UTF-8"?>
<results>
<object id="1">
<title>back parking lot</title>
<assets3d>
<model>
url1
</model>
<model>
url2
</model>
</assets3d>
</object>
</results>
解析器类,我NodeList models = myParser.getValue(e, "model",0);
用来获取模型
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 ){
Log.d("child.getNodeValue() ", "child.getNodeValue() "+child.getNodeValue());
return child.getNodeValue();
}
}
}
}
return "0000";
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
Log.d("this.getElementValue(n.item(0))", "this.getElementValue(n.item(0)) "+this.getElementValue(n.item(0)));
return this.getElementValue(n.item(0));
}
public NodeList getValue(Element item, String str,int a) {
NodeList n = item.getElementsByTagName(str);
Log.d("item.getElementsByTagName", "item.getElementsByTagName "+ n.getLength());
//return this.getElementValue(n.item(0));
return n;
}
}
}