How do I read variables from a remote server?
I am currently working on a littl开发者_StackOverflow社区e remote image viewer app.
What I need to know is how to read string variables from a Xml
file on a remote server and put them into a String[]
. So my program can use them how I want. All the variable in the Xml
file are strings (I.E "http://www.website.com/image.png")
I can do this with a local Xml
but how would I do this from a remote Xml
file?
One method is to use a SAX parser as described here http://www.codingforandroid.com/2010/12/reading-remote-xml-file-with-sax.html
I just had to load XML for an app I am working on. This is the method I am currently using. You have to change it to suit your XML structure, but this should give you a pretty good idea. I am still new to java and android, so their may be a better solution
private void loadXML()
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try
{
db = dbf.newDocumentBuilder();
try
{
Document doc = db.parse(new URL("http://yoursite.com/presentation.xml").openStream());
Element docElement = doc.getDocumentElement();
NodeList nl = docElement.getElementsByTagName("Slide");
if (nl != null && nl.getLength() > 0)
{
String slideArray[] = new String[nl.getLength()];
vforumLength = nl.getLength();
for (int i = 0; i < nl.getLength(); i++)
{
Element slideElement = (Element) nl.item(i);
NodeList titleList = slideElement.getElementsByTagName("Title");
Element titleElement = (Element) titleList.item(0);
String title = titleElement.getFirstChild().getNodeValue();
slideArray[i] = title;
Log.i("xml",title);
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
}
and the XML:
<?xml version="1.0" encoding="UTF-8"?>
<vForum>
<Slides>
<Slide id="1" tcIn="00:00:00.0" tcOut="00:00:00.0">
<Title>Title 1</Title>
</Slide>
<Slide id="2" tcIn="00:00:00.0" tcOut="00:00:00.0">
<Title>Title 2</Title>
</Slide>
<Slide id="3" tcIn="00:00:00.0" tcOut="00:00:00.0">
<Title>Title 3</Title>
</Slide>
<Slide id="4" tcIn="00:00:00.0" tcOut="00:00:00.0">
<Title>Title 4</Title>
</Slide>
<Slide id="5" tcIn="00:00:00.0" tcOut="00:00:00.0">
<Title>Title 5</Title>
</Slide>
</Slides>
</vForum>
my actual XML is a bit more complicated, but I trimmed it down so you dont have to go through the irrelevant data
精彩评论