2012-09-21 107 views
-3

我需要解析我的Android活動中的以下XML結構。我有它在字符串格式:簡單的Android XML解析任務

<Cube> 
    <Cube time="2012-09-20"> 
    <Cube currency='USD' rate='1.2954'/> 
    <Cube currency='JPY' rate='101.21'/> 
    <!-- More cube tags here --> 
    </Cube> 
</Cube> 

出於這個我想人名幣(美元,日元等),以及它們各自的利率的數組。可選地,按照上面指定的格式在XML文檔中僅出現一次的日期。請注意空立方體標籤也。也可能有其他奇怪的事件。我只需要獲取同時設置貨幣和費率的Cube代碼。

最好使用一些XML解析庫,而不是正則表達式,但如果它訴諸我也準備好使用它。

編輯: 這是我到目前爲止提出的。問題是將匹配的元素插入數組中,我不知道該怎麼做。

Pattern p = Pattern.compile("<Cube\\scurrency='(.*)'\\srate='(.*)'/>"); 
Matcher matcher = p.matcher(currency_source); 
while (matcher.find()) { 
    Log.d("mine", matcher.group(1)); 
} 
+0

你可以用'SAXParser'輕鬆做到這一點,實現'startElement'和'endElement'方法。 – Luksprog

+1

您有3個內置的解析XML的解析方法:DOM - ,SAX - 和Pullparser – Ahmad

+0

我已經使用正則表達式編輯了我的問題,因爲我在設置XML解析器類時遇到了一些問題。你能幫我從表達式中得到匹配的條目並將它們推入數組中嗎? –

回答

2

這裏是一個自定義的處理應該得到你想要的數據:

public class MyHandler extends DefaultHandler { 

    private String time; 
    // I would use a simple data holder object which holds a pair 
    // name-value(or a HashMap) 
    private ArrayList<String> currencyName = new ArrayList<String>(); 
    private ArrayList<String> currencyValue = new ArrayList<String>(); 

    @Override 
    public void startElement(String uri, String localName, String qName, 
       Attributes attributes) throws SAXException { 
     if (localName.equals("Cube")) { // it's a Cube!!! 
      // get the time 
      if (attributes.getIndex("", "time") != -1) { 
       // this Cube has the time!!! 
      time = attributes.getValue(attributes.getIndex("", "time")); 
      } else if (attributes.getIndex("", "currency") != -1 
       && attributes.getIndex("", "rate") != -1) { 
       // this Cube has both the desired values so get them!!! 
       // but first see if both values are set 
       String name = attributes.getValue(attributes.getIndex("", 
          "currency")); 
       String value = attributes.getValue(attributes.getIndex("", 
          "rate")); 
       if (name != null && value != null) { 
        currencyName.add(name); 
        currencyName.add(value); 
       } 
      } else { 
       // this Cube doesn't have the time or both the desired values. 
      } 
     } 
    } 

} 

然後,你可以用它沿着http://developer.android.com/reference/android/util/Xml.html或教程在那裏成千上萬的一個解析你的XML String