-1
網絡數據庫解析XML當我點擊一個按鈕,我想顯示一個XML文件已存儲在一個URL的數據庫,如何做到這一點,請給我一個例子。從我的應用程序中的Android
網絡數據庫解析XML當我點擊一個按鈕,我想顯示一個XML文件已存儲在一個URL的數據庫,如何做到這一點,請給我一個例子。從我的應用程序中的Android
讓服務器端腳本獲取服務器上的數據並將其作爲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解析器解析字符串轉換成文檔對象的簡短的腳本。
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;
}
}