我正在尝试从url中检索xml标记名中的内容,但我的int numberOfDetails长度为0.我做错了什么?
//编辑代码
public String[] dumpTitles(String[] xmlFiles) {
String[] elementsArray = null;
try {
URL xmlContent = new URL("http://webdev4.matcmadison.edu/mab/AmazonXML/georgeEliot.xml");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(xmlContent.openStream()));
Toast.makeText(this, "xml file: " + xmlContent, 1000).show();
NodeList detailsNodeList = doc.getElementsByTagName("Details");
int numberOfDetails = detailsNodeList.getLength();
String str = String.format("There are %d Details elements", numberOfDetails);
Log.println(Log.DEBUG, TAG, str);
Toast.makeText(this, "number of details: " + str, 1000).show();
elementsArray = getElementByTagName("ProductName", numberOfDetails, detailsNodeList);
}
catch (Exception ex) {
Log.println(Log.DEBUG, TAG, "XML Parsing failed: " + ex.getMessage());
}
return elementsArray;
}
public String[] getElementByTagName(String detailTagName, int numberOfDetails, NodeList detailsNodeList) throws Exception {
String[] elementsArray = null;
ArrayList<String> elementsArrayList = new ArrayList<String>();
Toast.makeText(this, "TEST2", 1000).show();
for (int k = 0; k < numberOfDetails; k++) {
Toast.makeText(this, "TEST3", 1000).show();
Element nDetails = (Element)detailsNodeList.item(k);
NodeList elementNodeList = ((Document) nDetails).getElementsByTagName(detailTagName);
Node nodeName = elementNodeList.item(k);
String nodeString = String.format("%s", nodeName);
elementsArrayList.add(nodeString);
elementsArray = elementsArrayList.toArray(elementsArray);
Log.println(Log.DEBUG, TAG, nodeString);
Toast.makeText(this, "TEST4", 1000).show();
Toast.makeText(this, "ELEMENT" + elementsArray[0], 1000).show();
}
return elementsArray;
}
//原始代码 String xmlContent =“http://webdev4.matcmadison.edu/mab/AmazonXML/georgeEliot.xml”; Log.println(Log.DEBUG,TAG,“FILE NAME:”+ xmlContent); String [] elementsArray = null; 尝试{ DocumentBuilder db = DocumentBuilderFactory.newInstance()。newDocumentBuilder(); Toast.makeText(this,“xml file:”+ xmlContent,1000).show(); Document doc = db.parse(new InputSource(new StringReader(xmlContent))); NodeList detailsNodeList = doc.getElementsByTagName(“Details”); int numberOfDetails = detailsNodeList.getLength();
答案 0 :(得分:3)
您不应使用StringReader
来读取网址。 StringReader
读取您在构造函数中传递的字符串,它不会从Web下载文件。您可以改为使用URL
类:
URL xmlContent = new URL("http://webdev4.matcmadison.edu/mab/AmazonXML/georgeEliot.xml");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(xmlContent.openStream()));
另一种方式:
您可以InputSource
String
String pathToDocument = "http://webdev4.matcmadison.edu/mab/AmazonXML/georgeEliot.xml";
Document doc = db.parse(new InputSource(pathToDocument));
使用{{1}}:
{{1}}