Не удается разобрать элемент из результата XML с использованием DOM - PullRequest
2 голосов
/ 05 марта 2011

Я использую сервис Google Weather API. Я использую DOM. У меня есть трудности, чтобы получить значение элемента.

это пример ответа xml:

<xml_api_reply version="1">
 <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">  
     <forecast_information>
         <city data="New York, NY"/>
         <postal_code data="new york,ny"/>
         <latitude_e6 data=""/>
         <longitude_e6 data=""/>
         <forecast_date data="2010-05-20"/>
         <current_date_time data="2010-05-20 07:44:43 +0000"/>
         <unit_system data="US"/>
     </forecast_information>
    <current_conditions>
        <condition data="Cloudy"/>
        <temp_f data="59"/>
        <temp_c data="15"/>
        <humidity data="Humidity: 80%"/>
        <icon data="/ig/images/weather/cloudy.gif"/>
        <wind_condition data="Wind: N at 0 mph"/>
    </current_conditions>
    <forecast_conditions>
        <day_of_week data="Thu"/>
        <low data="61"/>
        <high data="79"/>
        <icon data="/ig/images/weather/sunny.gif"/>
        <condition data="Sunny"/>
        </forecast_conditions>
    <forecast_conditions>
        <day_of_week data="Fri"/>
        <low data="60"/>
        <high data="83"/>
        <icon data="/ig/images/weather/partly_cloudy.gif"/>
        <condition data="Partly Cloudy"/>
    </forecast_conditions>
</weather>


Теперь, скажем, я хочу получить значение данных условия, которые находятся под тегом

(в этом примере я пытаюсь получить значение = "облачно"

вот что я делаю:

 void buildForecasts(String raw) throws Exception
{
    DocumentBuilder builder = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));

    NodeList temps = doc.getElementsByTagName("current_conditions");



    for (int i = 0; i < temps.getLength(); i++)
    {
        Element temp = (Element) temps.item(i);
        String temp1 =temp.getAttribute("condition")
    }

}

это действительно не работает для меня. У кого-нибудь есть идеи?

спасибо, лучей.

Ответы [ 2 ]

3 голосов
/ 05 марта 2011

Список temps содержит элементы с именем "current_conditions" (т. Е. Узел <current_conditions> в XML).Вам необходимо получить подэлемент с именем «условие» (то есть узел <condition data="Cloudy"/> в XML), а затем получить его атрибут data.

for (int i = 0; i < temps.getLength(); i++)
{
    Element currentConditionsElement = (Element) temps.item(i);
    NodeList conditionList = currentConditionsElement.getElementsByTagName("condition");
    Element conditionElement = (Element) conditionList.item(0);
    String dataAttribute = conditionElement.getAttribute("data");
}
1 голос
/ 05 марта 2011

Если вы используете API уровня 8 (Android 2.2), вы, вероятно, можете упростить ситуацию с помощью XPath.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...