Java 使用sax解析器解析子标记中的xml数据

Java 使用sax解析器解析子标记中的xml数据,java,xml,saxparser,Java,Xml,Saxparser,我是android新手,所以如果我问了一些愚蠢的问题,我很抱歉。我正在用android进行天气解析。我正在使用SAX解析器。现在,我一直在学习内容处理程序。通过这么多的教程,我想到了解析数据的方法,但所有这些示例都是基于XML文件的,该文件确实包含标记中的属性。对于从中检索数据的XML文件,标记中没有属性,只有子节点。现在我被困在这里,我不知道如何获得子节点的值 <data> <request> <type>City</type>

我是android新手,所以如果我问了一些愚蠢的问题,我很抱歉。我正在用android进行天气解析。我正在使用SAX解析器。现在,我一直在学习内容处理程序。通过这么多的教程,我想到了解析数据的方法,但所有这些示例都是基于XML文件的,该文件确实包含标记中的属性。对于从中检索数据的XML文件,标记中没有属性,只有子节点。现在我被困在这里,我不知道如何获得子节点的值

   <data>
   <request>
   <type>City</type>
   <query>Peshawar, Pakistan</query>
   </request>
   <current_condition>
   <observation_time>01:04 PM</observation_time>
   <temp_C>20</temp_C>
   <temp_F>68</temp_F>
   <weatherCode>113</weatherCode>
   <weatherIconUrl>
   </weatherIconUrl>

下面是一个从给定xml文件获取数据的解决方案

示例weather.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <request>
        <type>City</type>
        <query>Peshawar, Pakistan</query>
    </request>
    <current_condition>
        <observation_time>01:04 PM</observation_time>
        <temp_C>20</temp_C>
        <temp_F>68</temp_F>
        <weatherCode>113</weatherCode>
        <weatherIconUrl> a url </weatherIconUrl>
    </current_condition>
</data>
您可以使用以下代码检索数据:

HandlingXmlStuff handlingXmlStuf = new HandlingXmlStuff();
handlingXmlStuf.parseDocument();
System.out.println("type:" + handlingXmlStuf.getType() + ":type");
System.out.println("observation_time:" + handlingXmlStuf.getObservation_time() + ":observation_time");
System.out.println("temp_C:" + handlingXmlStuf.getTemp_C() + ":temp_C");
System.out.println("temp_F:" + handlingXmlStuf.getTemp_F() + ":temp_F");
System.out.println("weatherCode:" + handlingXmlStuf.getWeatherCode() + ":weatherCode");
System.out.println("weatherIconUrl:" + handlingXmlStuf.getWeatherIconUrl() + ":weatherIconUrl");

下面是从中提取值的完整解析解决方案

示例xml数据来自:


读取开始标记时,
startElement
调用,读取结束标记时,
endElement
调用,每次
startElement
endElement
方法调用后,
characters
方法调用。

发布完整的xml文件是sax您唯一的选择吗?非常感谢您,您帮了我很多。我不想问其他问题。。。在第二段代码中,u粘贴了whats weather.xml。我为我的项目安排了代码,但仍然不起作用。。如果我粘贴我所有的代码和解析数据的链接,你会帮我吗?@saman如果你觉得这篇文章有用,为什么不投你的票呢???。xml是一个包含您在帖子中包含的xml数据的文件。我已经发布了完整的答案作为一个单独的答案。上面u粘贴的代码可以使用java,但不能使用android。我已经在Facebook上给你发了一条信息,里面有我的项目文件。如果你对android有一些了解,请在这方面帮助我@visruth@saman我没有收到任何消息。您可以使用中的“联系我们”表单与我联系。正确填写表格,并在表格的消息字段中包含所有疑问。发布后,您将收到确认回复,然后您可以将项目代码回复到该邮件。那么,您是否在android清单文件中提供了必要的权限(如internet)?如果不给它。我如何解析图像形成相同的链接。除了显示图像外,它还显示链接。你能告诉我吗?哦,我的上帝。。谢谢谢谢谢谢。。首先,我将运行这个程序,在此基础上,我将在android中实现相同的代码。如果有任何问题,我会再次打扰你:这是我的android代码。它有三个类,我必须解析查询标记和临时标记。。它需要2个输入,即城市和州。然后,我将用户输入的城市和州附加到url。然后试图解析数据。。我正在尽我最大的努力,你也帮了我很多。这是代码。这是我的荣幸,但你必须投票支持这两个帮助你的帖子!!!!我看得出你现在的声望最低了。我建议你使用正确的英语,只使用英语。我无法理解你的第二个评论。什么是jux?@saman我想,首先你必须了解如何使用stackoverflow和它所说的规则。为什么要将这些代码作为不同的答案发布????如果您提出任何答案,这些答案必须是张贴问题的正确答案。而且你还必须在单一答案帖子中发布一个答案。你这样做不是件好事。如果您对相关代码有任何疑问,可以在问题栏中提问。很抱歉,请记住:如果您不遵守stackoverflow规则,您的帐户可能会被知名会员阻止/限制。
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author visruth
 */
public class HandlingXmlStuff extends DefaultHandler {

    private boolean typeStatus;
    private boolean queryStatus;
    private boolean observation_timeStatus;
    private boolean temp_CStatus;
    private boolean temp_FStatus;
    private boolean weatherCodeStatus;
    private boolean weatherIconUrlStatus;
    private String type;
    private String query;
    private String observation_time;
    private String temp_C;
    private String temp_F;
    private String weatherCode;
    private String weatherIconUrl;

    public String getObservation_time() {
        return observation_time;
    }

    public String getQuery() {
        return query;
    }

    public String getTemp_C() {
        return temp_C;
    }

    public String getTemp_F() {
        return temp_F;
    }

    public String getType() {
        return type;
    }

    public String getWeatherCode() {
        return weatherCode;
    }

    public String getWeatherIconUrl() {
        return weatherIconUrl;
    }

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

        if (qName.equals("type")) {
            typeStatus = true;
        } else {
            typeStatus = false;
        }

        if (qName.equals("query")) {
            queryStatus = true;
        } else {
            queryStatus = false;
        }

        if (qName.equals("observation_time")) {
            observation_timeStatus = true;
        } else {
            observation_timeStatus = false;
        }
        if (qName.equals("temp_C")) {
            temp_CStatus = true;
        } else {
            temp_CStatus = false;
        }

        if (qName.equals("temp_F")) {
            temp_FStatus = true;
        } else {
            temp_FStatus = false;
        }

        if (qName.equals("weatherCode")) {
            weatherCodeStatus = true;
        } else {
            weatherCodeStatus = false;
        }
        if (qName.equals("weatherIconUrl")) {
            weatherIconUrlStatus = true;
        } else {
            weatherIconUrlStatus = false;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (typeStatus) {
            this.type = new String(ch, start, length).trim();
            typeStatus = false;
        }

        if (queryStatus) {
            this.query = new String(ch, start, length).trim();
            queryStatus = false;
        }
        if (observation_timeStatus) {
            this.observation_time = new String(ch, start, length).trim();
            observation_timeStatus = false;
        }
        if (temp_CStatus) {
            this.temp_C = new String(ch, start, length).trim();
            temp_CStatus = false;
        }
        if (temp_FStatus) {
            this.temp_F = new String(ch, start, length).trim();
            temp_FStatus = false;
        }
        if (weatherCodeStatus) {
            this.weatherCode = new String(ch, start, length).trim();
            weatherCodeStatus = false;
        }
        if (weatherIconUrlStatus) {
            this.weatherIconUrl = new String(ch, start, length).trim();
            weatherIconUrlStatus = false;
        }

    }

    public void parseDocument() {
        //get a factory
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try {
            //get a new instance of parser
            SAXParser sp = spf.newSAXParser();

            //parse the file and also register this class for call backs
            sp.parse(TestCase.class.getResource("wheather.xml").getPath(), this);
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}
HandlingXmlStuff handlingXmlStuf = new HandlingXmlStuff();
handlingXmlStuf.parseDocument();
System.out.println("type:" + handlingXmlStuf.getType() + ":type");
System.out.println("observation_time:" + handlingXmlStuf.getObservation_time() + ":observation_time");
System.out.println("temp_C:" + handlingXmlStuf.getTemp_C() + ":temp_C");
System.out.println("temp_F:" + handlingXmlStuf.getTemp_F() + ":temp_F");
System.out.println("weatherCode:" + handlingXmlStuf.getWeatherCode() + ":weatherCode");
System.out.println("weatherIconUrl:" + handlingXmlStuf.getWeatherIconUrl() + ":weatherIconUrl");
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <request>
        <type>City</type>
        <query>Peshawar, Pakistan</query>
    </request>
    <current_condition>
        <observation_time>04:31 AM</observation_time>
        <temp_C>7</temp_C>
        <temp_F>45</temp_F>
        <weatherCode>113</weatherCode>
        <weatherIconUrl><![CDATA[http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
        </weatherIconUrl>
        <weatherDesc><![CDATA[Sunny]]>
        </weatherDesc>
        <windspeedMiles>0</windspeedMiles>
        <windspeedKmph>0</windspeedKmph>
        <winddirDegree>0</winddirDegree>
        <winddir16Point>N</winddir16Point>
        <precipMM>0.0</precipMM>
        <humidity>70</humidity>
        <visibility>4</visibility>
        <pressure>1021</pressure>
        <cloudcover>0</cloudcover>
    </current_condition>
    <weather>
        <date>2013-01-26</date>
        <tempMaxC>22</tempMaxC>
        <tempMaxF>71</tempMaxF>
        <tempMinC>7</tempMinC>
        <tempMinF>45</tempMinF>
        <windspeedMiles>8</windspeedMiles>
        <windspeedKmph>13</windspeedKmph>
        <winddirection>NW</winddirection>
        <winddir16Point>NW</winddir16Point>
        <winddirDegree>315</winddirDegree>
        <weatherCode>113</weatherCode>
        <weatherIconUrl><![CDATA[http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
        </weatherIconUrl>
        <weatherDesc><![CDATA[Sunny]]>
        </weatherDesc>
        <precipMM>0.0</precipMM>
    </weather>
    <weather>
        <date>2013-01-27</date>
        <tempMaxC>20</tempMaxC>
        <tempMaxF>68</tempMaxF>
        <tempMinC>8</tempMinC>
        <tempMinF>46</tempMinF>
        <windspeedMiles>7</windspeedMiles>
        <windspeedKmph>12</windspeedKmph>
        <winddirection>N</winddirection>
        <winddir16Point>N</winddir16Point>
        <winddirDegree>352</winddirDegree>
        <weatherCode>113</weatherCode>
        <weatherIconUrl><![CDATA[http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
        </weatherIconUrl>
        <weatherDesc><![CDATA[Sunny]]>
        </weatherDesc>
        <precipMM>0.0</precipMM>
    </weather>
    <weather>
        <date>2013-01-28</date>
        <tempMaxC>20</tempMaxC>
        <tempMaxF>68</tempMaxF>
        <tempMinC>7</tempMinC>
        <tempMinF>45</tempMinF>
        <windspeedMiles>9</windspeedMiles>
        <windspeedKmph>14</windspeedKmph>
        <winddirection>NW</winddirection>
        <winddir16Point>NW</winddir16Point>
        <winddirDegree>316</winddirDegree>
        <weatherCode>113</weatherCode>
        <weatherIconUrl><![CDATA[http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
        </weatherIconUrl>
        <weatherDesc><![CDATA[Sunny]]>
        </weatherDesc>
        <precipMM>0.0</precipMM>
    </weather>
    <weather>
        <date>2013-01-29</date>
        <tempMaxC>21</tempMaxC>
        <tempMaxF>70</tempMaxF>
        <tempMinC>8</tempMinC>
        <tempMinF>46</tempMinF>
        <windspeedMiles>6</windspeedMiles>
        <windspeedKmph>9</windspeedKmph>
        <winddirection>NW</winddirection>
        <winddir16Point>NW</winddir16Point>
        <winddirDegree>306</winddirDegree>
        <weatherCode>113</weatherCode>
        <weatherIconUrl><![CDATA[http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
        </weatherIconUrl>
        <weatherDesc><![CDATA[Sunny]]>
        </weatherDesc>
        <precipMM>0.0</precipMM>
    </weather>
    <weather>
        <date>2013-01-30</date>
        <tempMaxC>19</tempMaxC>
        <tempMaxF>66</tempMaxF>
        <tempMinC>8</tempMinC>
        <tempMinF>47</tempMinF>
        <windspeedMiles>8</windspeedMiles>
        <windspeedKmph>13</windspeedKmph>
        <winddirection>WNW</winddirection>
        <winddir16Point>WNW</winddir16Point>
        <winddirDegree>289</winddirDegree>
        <weatherCode>116</weatherCode>
        <weatherIconUrl><![CDATA[http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png]]>
        </weatherIconUrl>
        <weatherDesc><![CDATA[Partly Cloudy ]]>
        </weatherDesc>
        <precipMM>0.0</precipMM>
    </weather>
</data>
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author visruth
 */
public class HandlingXmlStuff extends DefaultHandler {

    private String key;
    private Map<String, String> request = new HashMap<String, String>();
    private Map<String, String> current_condition = new HashMap<String, String>();
    private List<Map<String, String>> weather = new ArrayList<Map<String, String>>();
    private Map<String, String> weatherMap;
    private boolean requestStatus;
    private boolean current_conditionStatus;
    private boolean weatherStatus;

    public Map<String, String> getCurrent_condition() {
        return this.current_condition;
    }

    public Map<String, String> getRequest() {        
        return this.request;
    }

    public List<Map<String, String>> getWeather() {        
        return this.weather;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        key = qName;
        if (qName.equals("request")) {

            requestStatus = true;
        } else if (qName.equals("current_condition")) {

            current_conditionStatus = true;
        } else if (qName.equals("weather")) {
            weatherMap = new HashMap<String, String>();
            weatherStatus = true;
        }        

    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {

        String value = new String(ch, start, length).trim();
        if (requestStatus) {
            if (!key.trim().equals("request") && !key.trim().isEmpty() && !value.isEmpty()) {
                request.put(key, value);
            }            
        } else if (current_conditionStatus) {
            if (!key.trim().equals("current_condition") && !key.trim().isEmpty() && !value.isEmpty()) {
                current_condition.put(key, new String(ch, start, length).trim());
            }
        } else if (weatherStatus) {
            if (!key.trim().equals("weather") && !key.trim().isEmpty() && !value.isEmpty()) {
                weatherMap.put(key, new String(ch, start, length).trim());
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (qName.equals("request")) {
            requestStatus = false;
        } else if (qName.equals("current_condition")) {
            current_conditionStatus = false;
        } else if (qName.equals("weather")) {
            weather.add(weatherMap);
            weatherStatus = false;            
        }
    }

    public void parseDocument() {
        //get a factory
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try {
            //get a new instance of parser
            SAXParser sp = spf.newSAXParser();            
            //parse the file and also register this class for call backs
            sp.parse("http://free.worldweatheronline.com/feed/weather.ashx?q=peshawar,pakistan&format=xml&num_of_days=5&key=eab9f57359164426132301", this);
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}
HandlingXmlStuff handlingXmlStuf = new HandlingXmlStuff();
handlingXmlStuf.parseDocument();
System.out.println("----values inside request tag-----");
Map<String, String> request = handlingXmlStuf.getRequest();
for (String key : request.keySet()) {
    System.out.println(key + ":" + request.get(key) + ":" + key);
}
System.out.println("----values inside current_condition tag-----");
Map<String, String> current_condition = handlingXmlStuf.getCurrent_condition();
for (String key : current_condition.keySet()) {
    System.out.println(key + ":" + current_condition.get(key) + ":" + key);
}

List<Map<String, String>> weather = handlingXmlStuf.getWeather();
for (Map<String, String> map : weather) {
    System.out.println("\n----each set of weather-----start");
    for (String key : map.keySet()) {
        System.out.println(key + ":" + map.get(key) + ":" + key);
    }
    System.out.println("----each set of weather-----end");
}
----values inside request tag-----
query:Peshawar, Pakistan:query
type:City:type
----values inside current_condition tag-----
cloudcover:0:cloudcover
observation_time:04:31 AM:observation_time
pressure:1021:pressure
temp_C:7:temp_C
visibility:4:visibility
temp_F:45:temp_F
windspeedMiles:0:windspeedMiles
precipMM:0.0:precipMM
winddirDegree:0:winddirDegree
winddir16Point:N:winddir16Point
weatherIconUrl:http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png:weatherIconUrl
humidity:70:humidity
windspeedKmph:0:windspeedKmph
weatherCode:113:weatherCode
weatherDesc:Sunny:weatherDesc

----each set of weather-----start
windspeedMiles:8:windspeedMiles
winddirection:NW:winddirection
date:2013-01-26:date
precipMM:0.0:precipMM
winddir16Point:NW:winddir16Point
winddirDegree:315:winddirDegree
weatherIconUrl:http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png:weatherIconUrl
tempMinC:7:tempMinC
windspeedKmph:13:windspeedKmph
tempMaxC:22:tempMaxC
weatherCode:113:weatherCode
tempMaxF:71:tempMaxF
tempMinF:45:tempMinF
weatherDesc:Sunny:weatherDesc
----each set of weather-----end

----each set of weather-----start
windspeedMiles:7:windspeedMiles
winddirection:N:winddirection
date:2013-01-27:date
precipMM:0.0:precipMM
winddir16Point:N:winddir16Point
winddirDegree:352:winddirDegree
weatherIconUrl:_0001_sunny.png:weatherIconUrl
tempMinC:8:tempMinC
windspeedKmph:12:windspeedKmph
tempMaxC:20:tempMaxC
weatherCode:113:weatherCode
tempMaxF:68:tempMaxF
tempMinF:46:tempMinF
weatherDesc:Sunny:weatherDesc
----each set of weather-----end

----each set of weather-----start
windspeedMiles:9:windspeedMiles
winddirection:NW:winddirection
date:2013-01-28:date
precipMM:0.0:precipMM
winddir16Point:NW:winddir16Point
winddirDegree:316:winddirDegree
weatherIconUrl:http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png:weatherIconUrl
tempMinC:7:tempMinC
windspeedKmph:14:windspeedKmph
tempMaxC:20:tempMaxC
weatherCode:113:weatherCode
tempMaxF:68:tempMaxF
tempMinF:45:tempMinF
weatherDesc:Sunny:weatherDesc
----each set of weather-----end

----each set of weather-----start
windspeedMiles:6:windspeedMiles
winddirection:NW:winddirection
date:2013-01-29:date
precipMM:0.0:precipMM
winddir16Point:NW:winddir16Point
winddirDegree:306:winddirDegree
weatherIconUrl:http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png:weatherIconUrl
tempMinC:8:tempMinC
windspeedKmph:9:windspeedKmph
tempMaxC:21:tempMaxC
weatherCode:113:weatherCode
tempMaxF:70:tempMaxF
tempMinF:46:tempMinF
weatherDesc:Sunny:weatherDesc
----each set of weather-----end

----each set of weather-----start
windspeedMiles:8:windspeedMiles
winddirection:WNW:winddirection
date:2013-01-30:date
precipMM:0.0:precipMM
winddir16Point:WNW:winddir16Point
winddirDegree:289:winddirDegree
weatherIconUrl:unny_intervals.png:weatherIconUrl
tempMinC:8:tempMinC
windspeedKmph:13:windspeedKmph
tempMaxC:19:tempMaxC
weatherCode:116:weatherCode
tempMaxF:66:tempMaxF
tempMinF:47:tempMinF
weatherDesc:Partly Cloudy:weatherDesc
----each set of weather-----end