【发布时间】:2011-03-27 19:20:51
【问题描述】:
在我的应用程序中,当我单击一个按钮时,我想显示一个 xml 文件,该文件存储在一个 url 的数据库中,如何做到这一点,请给我一个例子。
【问题讨论】:
标签: android database url networking xml-parsing
在我的应用程序中,当我单击一个按钮时,我想显示一个 xml 文件,该文件存储在一个 url 的数据库中,如何做到这一点,请给我一个例子。
【问题讨论】:
标签: android database url networking xml-parsing
让服务器端脚本获取服务器上的数据并将其作为 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;
}
}
【讨论】: