我想直接在我自己的目录中从 Web 服务器下载一个 XML 文件。
我在内部存储中创建新文件夹的代码是
File mydir = context.getDir("LENOX",Context.MODE_PRIVATE);
File fileWithinDir = new File(mydir,"LENOX.xml");
我的 XML 文件下载类:
public class XMLParser {
ConnectionDetector cd = new ConnectionDetector(ListViewActivity.getAppContext());
public String getXMLFromUrl(String url) {
String xml = null;
if (cd.isConnectingToInternet()) {
try {
//defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
return null;
}
return xml;
//return xml
}
public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(new ByteArrayInputStream(xml.getBytes()));
} catch (ParserConfigurationException e) {
Log.e("Error Parser: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error SAX: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error IO: ", e.getMessage());
return null;
}
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
从这里
代码片段......也许它有助于理解
XMLParser parser = new XMLParser();
String xml = parser.getXMLFromUrl("http://testsite.de/XXX.xml");
是否有任何代码片段用于从下载的 xml 文件在我自己的目录中创建文件?