有很多方法可以获取 xml 内容我给你我的方式:
您需要前 3 个主要方法:
方法一:
public static String getXML(String url){
String line = null;
Log.d("-----URL STATE -----","Start getXML");
try {
URL u = new URL (url);
HttpURLConnection huc = ( HttpURLConnection ) u.openConnection ();
huc.setRequestMethod ("GET"); //OR huc.setRequestMethod ("HEAD");
huc.connect () ;
int code = huc.getResponseCode() ;
System.out.println(code);
Log.d("-----URL STATE -----","Checking URL");
if (code==404){
line="Wrong URL";
Log.d("-----URL STATE -----"," Wrong URL"+code);
}else{
//-------------------
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
}
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
方法二:
public final static Document XMLfromString(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(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
方法3:
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
使用 :
String xml = getXML(url);
Document doc =XMLfromString(xml);
NodeList nodes = doc.getElementsByTagName(yourTAG); //TAG you want to get as String
ArrayList<String> TAGS=new ArrayList<String>();
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
TAGS.add(getValue(e,yourTAG.toString());
}
现在您可以使用 “标签”
并且在一切之前始终记住“StrictMode.setThreadPolicy” :
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}