2011-03-05 6 views
2

Google 날씨 API 서비스를 사용하고 있습니다. DOM을 사용하고 있습니다. 요소 값을 가져 오는 데 어려움이 있습니다. 이에 (지금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> 


의 내가 태그

아래 조건 데이터의 값을 검색 할 가정 해 봅시다 :

는 XML 응답의 예를 먹으 렴 예를 들어 값 = "흐림"을 얻으려고 시도합니다.

이것이 제가하는 일입니다.

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") 
    } 

} 

은 나를 위해 정말 일을 나던. 누구든지 어떤 생각을 가지고 있니?

감사합니다. 레이.

답변

3

temps 목록에는 이름이 "current_conditions"인 요소 (즉, XML에 노드 <current_conditions>)가 포함되어 있습니다. 'condition'이라는 하위 요소 (즉 XML에 노드 <condition data="Cloudy"/>)를 가져와 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"); 
} 
+0

감사합니다. 그냥 마지막 줄에 (요소) 캐스팅을 넣어야합니다. – rayman

+0

감사합니다. 내 대답을 편집 할게. –

1

API 수준 8 (Android 2.2)을 사용하는 경우 XPath를 사용하여 단순화 할 수 있습니다.

+0

결코 그것을 시도하지 마십시오 be4, 아픈, 고마워. – rayman

+0

XML에서 정보를 추출하는 것이 좋지만 XML 수정 또는 작성에는 사용되지 않습니다. 행운을 빕니다! –

+0

내가 좋은 샘플을 어디에서 찾을 수 있는지 아십니까? – rayman

관련 문제