我如何在android中解析这些xml文件值

时间:2011-11-25 06:58:44

标签: android xml-parsing

我有一个xml文件......

<?xml version="1.0" ?> 
-<dict>
   <ID>USDUSD</ID> 
   <VALUE>0.00</VALUE> 
   <ID>USDGBP</ID> 
   <VALUE>0.6465</VALUE> 
   <ID>USDEUR</ID> 
   :
   :
</dict>

我尝试使用以下代码

的sax解析器
private boolean getUpdatedCurrencyValue(Context context) {
    try {

        /** Handling XML */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /** Send URL to parse XML Tags */

        URL sourceUrl = new URL("http:..../currencyconv.php");
        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        XMLHandler myXMLHandler = new XMLHandler();
        xr.setContentHandler(myXMLHandler);
        InputSource is=new InputSource(sourceUrl.openStream());
        Log.d("DEBUG",""+is);
        xr.parse(is);
        if(myMap!=null){
              myMap.clear();
        }  


        for (int i = 0; i < XMLHandler.countriesNames.size(); i++) {
            myMap.put(XMLHandler.countriesNames.get(i), XMLHandler.currencyValues.get(i));
             log(XMLHandler.countriesNames.get(i)+"  "+ XMLHandler.currencyValues.get(i));
        }

    } catch (Exception e) {
        e.printStackTrace();
        isError=true;


    }
}



public class XMLHandler extends DefaultHandler{

int counter=0;
protected static ArrayList<String> backupCurrencyValues = new ArrayList<String>();

//protected static String[] currencyValues=new String[290];
protected static ArrayList<String> currencyValues = new ArrayList<String>();
protected static ArrayList<String> countriesNames = new ArrayList<String>();
   //   private String[] countriesNames=new String[290];
  public XMLHandler() {
    counter=0;
  }


@Override
public void characters(char ch[], int start, int length) {
        String temp=new String(ch,start,length); //  this function retrieves values a from a tag each time
        Log.d("CURRENCY","Original "+temp);

        }

}

此函数每次从标记中检索值

但想要基于标签的值..有什么帮助?

1 个答案:

答案 0 :(得分:2)

您的意思是从标签中检索标签属性值吗?

您可能想参考我当前的XML解析文章系列:https://xjaphx.wordpress.com/learning/tutorials/