所以在您的指南后我将代码更改为此但应用程序只是挂起... 从这里开始下一步是什么?从
调用getXMLDocument xml = XMLemailF.getXML();
public static Document getXML(){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// get a document builder
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//parse using builder to get DOM representation of the XML file
Document doc = null;
try {
doc = db.parse("/xxxxxx/res/xml/email.xml");
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
这叫做
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
通过这个
...
Document xml = XMLemailF.getXML();
int numResults = XMLemailF.numResults(xml);
if((numResults <= 0)){
Toast.makeText(contactus_email.this, "No results found", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = xml.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("email", XMLemailF.getValue(e, "email"));
map.put("line1", XMLemailF.getValue(e, "line1"));
mylist.add(map);
...
有什么想法吗?
答案 0 :(得分:0)
您是否需要从本地文件中获取xml DOM?我明白了吗?
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream("/path/to/your/file.xml");
或
Document doc = builder.parse(getClass().getResourceAsStream("/path/to/your/resource.xml"));
答案 1 :(得分:0)
当然可以
尝试类似:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// get a document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
Document doc = db.parse("yourFile.xml");
并查看这些类的javadoc以获取更多信息
答案 2 :(得分:0)
以下是使用SAXPArser读取sdcard上的xml文件的方法
public static RSSFeed parseLocalXml(String filename){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RSSHandler theRssHandler = new RSSHandler();
xmlreader.setContentHandler(theRssHandler);
InputSource is = new InputSource(new FileInputStream(filename));
xmlreader.parse(is);
return theRssHandler.getFeed();//this is handler that reads trough xml nodes
} catch (Exception ee) {
return null;
}
}
答案 3 :(得分:0)
使用 application.getResourceAsStream(&#34;您的文件名&#34;),如下所示:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(application.getResourceAsStream("file.xml"));