简体   繁体   English

使用具有两个节点的sax解析器解析文件具有相同的名称

[英]parsing file using sax parser with two nodes have the same name

I'm parsing yahooweather api using saxparser 我正在使用saxparser解析yahooweather api

<yweather:forecast day="Sun" date="30 Jun 2013" low="22" high="34" text="Sunny" code="32"/>
<yweather:forecast day="Mon" date="1 Jul 2013" low="22" high="33" text="Sunny" code="32"/>
<yweather:forecast day="Tue" date="2 Jul 2013" low="22" high="33" text="Partly Cloudy" code="30"/>
<yweather:forecast day="Wed" date="3 Jul 2013" low="23" high="36" text="Sunny" code="32"/>

using this code: 使用此代码:

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {

    if (qName.equalsIgnoreCase("yweather:forecast")){

        day1.add(attributes.getValue("day")); 
        day1.add(attributes.getValue("date"));
        day1.add(attributes.getValue("low"));
        day1.add(attributes.getValue("high"));
        day1.add(attributes.getValue("text"));
        day1.add(attributes.getValue("code"));      

        info.setweather(day1.get(0),day1.get(1),day1.get(2),day1.get(3),day1.get(4),day1.get(5));
    }
}

I can now get the first day. 我现在可以得到第一天。 But I only want to get the second day, also not the other four days and put it in another array . 但是我只想获得第二天,而不是其他四天,然后将其放在另一个数组中。

Assuming that the order of the XML nodes is enough to figure out what the second day is: 假设XML节点的顺序足以确定第二天是什么:

Simply count how often you found the start of a yweather:forecast element. 只需数一下您发现yweather:forecast元素开始的yweather:forecast

private int currentDay;

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {

    if (qName.equalsIgnoreCase("yweather:forecast")){
        if (currentDay++ != 1) return;
        // rest of your code

Also reset or init the counter at each document start or end. 还要在每个文档的开始或结束处重置或初始化计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM