Background
We need simple access to XML to parse XML documents. So you just have to know where the results are in the XML document code and then parse it. For example, in the following picture, we want to know about the weather in Sfax, Tunisia:
In the beginning, we need to specify the city or state where we want to know the weather.
The code is as follows |
Copy Code |
String C = City.gettext (). toString (); String s = State.gettext (). toString (); StringBuilder URL = new StringBuilder (BaseURL); Url.append (c+ "," +s); String fullurl= url.tostring (); Try { URL website= new URL (fullurl); Getting XmlReader to parse data SAXParserFactory spf= saxparserfactory.newinstance (); SAXParser sp = Spf.newsaxparser (); XMLReader XR = Sp.getxmlreader (); Handlingxmlstuff doingwork = new Handlingxmlstuff (); Xr.setcontenthandler (doingwork); Xr.parse (New InputSource (Website.openstream ())); String information = Doingwork.getinformation (); Tv.settext (information); } catch (Exception e) { Tv.settext ("error"); } |
Then we start parsing the XML document.
The code is as follows |
Copy Code |
public class Handlingxmlstuff extends DefaultHandler { xmldatacollected info = new xmldatacollected (); Public String getinformation () { return info.datatostring (); }
@Override public void Startelement (string uri, String localname, String qName, Attributes Attributes) throws Saxexception { if (Localname.equals ("City")) { String city=attributes.getvalue ("data"); Info.setcity (city); }else if (localname.equals ("Temp_f")) { String t = attributes.getvalue ("Data"); int temp = Integer.parseint (t); Info.settemp (temp); } } } |
We need to specify our data model and the functionality used.
The
code is as follows |
copy code |
public class Xmldatacollected { int temp= 0; String City=null; public void setcity (String c) { city= C; } public void settemp (int t) { & nbsp temp = t; } public String datatostring () { return "in" +city+ "the" "The" "" "" "" "+ temp+" degrees "; } }. |
Points of interest
In this scenario, you learned how to use XML parsing in Android applications to easily make many features