2012-09-21 109 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