在我的应用程序中,当我单击一个按钮时,我想显示一个存储在URL数据库中的xml文件,该怎么做,请给我一个例子。
答案 0 :(得分:1)
让服务器端脚本获取服务器上的数据并将其作为XML返回。然后下载页面并将其加载到您的应用程序中。
使用此代码,您可以从在线数据库中获取xml文件,并将其解析为Android中的xml文档。
Document xmlDocument = fromString(downloadPage("http://example.com/data.php");
这是一个简短的脚本,应该下载一个网页并将其作为字符串返回
public String downloadPage(String targetUrl)
{
BufferedReader in = null;
try
{
// Create a URL for the desired page
URL url = new URL(targetUrl);
// Read all the text returned by the server
in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
String output = "";
while ((str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline
// character(s)
output += "\n";
output += str;
}
return output.substring(1);
}
catch (MalformedURLException e)
{}
catch (IOException e)
{}
finally
{
try
{
if (in != null) in.close();
}
catch (IOException e)
{
}
}
return null;
}
这是一个简单的DOM解析器,用于将字符串解析为Document对象。
public static Document fromString(String xml)
{
if (xml == null)
throw new NullPointerException("The xml string passed in is null");
// from http://www.rgagnon.com/javadetails/java-0573.html
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document doc = db.parse(is);
return doc;
}
catch (SAXException e)
{
return null;
}
catch(Exception e)
{
CustomExceptionHandler han = new CustomExceptionHandler();
han.uncaughtException(Thread.currentThread(), e);
return null;
}
}