Search code examples
androidparsinggetsaxchild-nodes

SAX parsing android : how to get child nodes


I want to get data from XML file :https://www.vietcombank.com.vn/exchangerates/ExrateXML.aspx

the error is i can get the last element USD and pass the others. Please help me

here is my all class: Exrate.java

 public class Exrate {
    String CurrencyCode;
    String CurrencyName;
    String Buy;
    String Transfer;
    String Sell;

    public Exrate(){}

    public String getCurrencyCode() {
        return CurrencyCode;
    }
    public void setCurrencyCode(String CurrencyCode) {
        this.CurrencyCode = CurrencyCode;
    }
    //
    public String getCurrencyName(){
        return CurrencyName;
    }
    public void setCurrencyName(String CurrencyName){
        this.CurrencyName=CurrencyName;
    }
    //
    public String getBuy(){
        return Buy;
    }
    public void setBuy(String Buy ){
        this.Buy=Buy;
    }
    //
    public String getTransfer(){
        return Transfer;
    }
    public void setTransfer(String Transfer ){
        this.Transfer=Transfer;
    }
    //
    public String getSell(){
        return Sell;
    }
    public void setSell(String Sell ){
        this.Sell=Sell;
    }
}

ExrateList.java

    public class ExrateList {
    String Datetime;
    Exrate exrate;
    public ExrateList(){}

    public String getDatetime(){
        return Datetime;
    }
    public void setDatetime(String DateTime){
        this.Datetime=DateTime;
    }
    //
    public Exrate getExrate(){
        return exrate;
    }
    public void setExrate(Exrate exrate){
        this.exrate=exrate;
    }

}

SaxHandler.java

    public class SaxHandler extends DefaultHandler {

    String reading;
    ArrayList<ExrateList> exrateLists;
    ExrateList exrateList;
    Exrate exrate;
    public SaxHandler() {
        exrateLists = new ArrayList<ExrateList>();
    }



    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("ExrateList")){
                exrateLists=new ArrayList<>();
                exrateList=new ExrateList();
        }
        if (qName.equalsIgnoreCase("Exrate")){
            exrate=new Exrate();
            exrate.setCurrencyCode(attributes.getValue("CurrencyCode"));
            exrate.setCurrencyName(attributes.getValue("CurrencyName"));
            exrate.setBuy(attributes.getValue("Buy"));
            exrate.setTransfer(attributes.getValue("Transfer"));
            exrate.setSell(attributes.getValue("Sell"));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("ExrateList")){
            if (exrateLists!=null){
                exrateLists.add(exrateList);
                exrateList=null;
            }
        }
         if (qName.equalsIgnoreCase("DateTime")){
            exrateList.setDatetime(reading);
        }
        else if (qName.equalsIgnoreCase("Exrate")){
            exrateList.setExrate(exrate);

        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        reading=new String(ch, start, length);
    }

    public List<ExrateList> getExrateLists() {
        return exrateLists;
    }
}

MySaxParser.java

    public class MySaxParser {
    public List<ExrateList> XMLparse(InputStream is) {
        List<ExrateList> exrateLists = null;
        try {
            // create a XMLReader from SAXParser
            XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            // create a SAXXMLHandler
            SaxHandler saxHandler = new SaxHandler();
            // store handler in XMLReader
            xmlReader.setContentHandler(saxHandler);
            // the process starts
            xmlReader.parse(new InputSource(is));
            // get the `Employee list`
            exrateLists =saxHandler.getExrateLists();

        } catch (Exception ex) {
            Log.d("XML", "SAXXMLParser: parse() failed");
        }

        // return Employee list
        return exrateLists;
    }
}

MainActivity.java

    public class MainActivity extends AppCompatActivity {
    TextView ngay, chuoi;
    String duongdan = "https://www.vietcombank.com.vn/exchangerates/ExrateXML.aspx";
    List<ExrateList> exrateLists = new ArrayList<ExrateList>();
    String datetime;
    String macode="";
    String tencode="";
    String mua="";
    InputStream is;
    URL url;
    URLConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ngay = (TextView) findViewById(R.id.textView);
        chuoi = (TextView) findViewById(R.id.textView2);
        Task a=new Task();
        a.execute();
    }

    class Task extends AsyncTask<Void,Void,Void>
    {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                url=new URL(duongdan);
                connection=url.openConnection();
                is=connection.getInputStream();
                MySaxParser mySaxParser=new MySaxParser();
                exrateLists=mySaxParser.XMLparse(is);
                //
                datetime=exrateLists.get(0).getDatetime();

                for(int i=0;i<exrateLists.size();i++) {

                    macode+=exrateLists.get(i).getExrate().getCurrencyCode();
                    tencode+= exrateLists.get(i).getExrate().getCurrencyName()+"\n";
                    mua+= exrateLists.get(i).getExrate().getBuy();

                }


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ngay.setText(datetime);
            chuoi.setText(macode+" "+tencode+" "+mua);

        }
    }

}

Solution

  • I have used simple framework to show this example that how you can read the xml tag.

    Create two classes which will help us create the Object which will act as Model classes.

    import org.simpleframework.xml.Attribute;
    import org.simpleframework.xml.Root;
    
    /**
     * Created by Pankaj Nimgade on 29-01-2016.
     */
    @Root (name = "Exrate", strict = false)
    public class Exrate {
        @Attribute(required = false)
        private String CurrencyCode;
    
        @Attribute(required = false)
        private String CurrencyName;
    
        @Attribute(required = false)
        private String Buy;
    
        @Attribute(required = false)
        private String Transfer;
    
        @Attribute(required = false)
        private String Sell;
    
        public Exrate() {
        }
    
        public Exrate(String currencyCode, String currencyName, String buy, String transfer, String sell) {
            CurrencyCode = currencyCode;
            CurrencyName = currencyName;
            Buy = buy;
            Transfer = transfer;
            Sell = sell;
        }
    
        public String getCurrencyCode() {
            return CurrencyCode;
        }
    
        public String getCurrencyName() {
            return CurrencyName;
        }
    
        public String getBuy() {
            return Buy;
        }
    
        public String getTransfer() {
            return Transfer;
        }
    
        public String getSell() {
            return Sell;
        }
    }
    

    ExrateList

    import org.simpleframework.xml.Element;
    import org.simpleframework.xml.ElementList;
    import org.simpleframework.xml.Root;
    
    import java.util.List;
    
    /**
     * Created by Pankaj Nimgade on 29-01-2016.
     */
    @Root (name = "ExrateList", strict = false)
    public class ExrateList {
        @Element(required = false)
        private String DateTime;
    
        @ElementList (inline = true,required= false)
        private List<Exrate> Exrate;
    
        @Element(required = false)
        private String Source;
    
        public ExrateList() {
        }
    
        public ExrateList(String dateTime, String source) {
            DateTime = dateTime;
            Source = source;
        }
    
        public String getDateTime() {
            return DateTime;
        }
    
        public List<Exrate> getList() {
            return Exrate;
        }
    
        public String getSource() {
            return Source;
        }
    }
    

    now you can test the code

    public class ReadXML {
    
        public static void main(String[] args) {
            try {
                Path paths = Paths.get("");
                String project_Path = paths.toAbsolutePath().toString();
                System.out.println("" + project_Path);
                File file = new File(project_Path + "\\excel_files\\some.xml");
                Serializer serializer = new Persister();
    
                ExrateList example = serializer.read(ExrateList.class, file);
                System.out.println("" + example.getDateTime());
                for (Exrate exrate:example.getList()) {
                    System.out.println(""+exrate.getCurrencyName()+"\t "+exrate.getCurrencyCode()+"\t "+exrate.getTransfer()+"\t "+exrate.getBuy()+"\t "+exrate.getSell());
                }
                System.out.println("" + example.getSource());
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Outout

    1/29/2016 4:11:40 PM
    AUST.DOLLAR AUD 15731.66 15637.27
    CANADIAN DOLLAR CAD 15768.98 15627.06
    SWISS FRANCE CHF 21700.14 21548.24
    DANISH KRONE DKK 3191.26 0
    EURO EUR 24068.25 23996.05
    BRITISH POUND GBP 31737.38 31515.22
    HONGKONG DOLLAR HKD 2831.9 2812.08
    INDIAN RUPEE INR 320.61 0
    JAPANESE YEN JPY 182.95 181.12
    SOUTH KOREAN WON KRW 18.48 0
    KUWAITI DINAR KWD 72009.45 0
    MALAYSIAN RINGGIT MYR 5340.84 0
    NORWEGIAN KRONER NOK 2536.44 0
    RUSSIAN RUBLE RUB 267.7 0
    SAUDI RIAL SAR 5745.75 0
    SWEDISH KRONA SEK 2573.7 0
    SINGAPORE DOLLAR SGD 15520.44 15411.8
    THAI BAHT THB 609.21 609.21
    US DOLLAR USD 22165 22165
    Joint Stock Commercial Bank for Foreign Trade of Vietnam - Vietcombank