2011-03-05 77 views
2

我正在使用Google天氣API服務。我正在使用DOM。 我很難獲取元素值。無法使用DOM解析XML結果中的元素

這就是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") 
    } 

} 

它不真的爲我工作。任何人有任何想法?

謝謝, 射線。

回答

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 2011-03-05 12:01:20

+0

謝謝。我會編輯我的答案。 – 2011-03-05 12:05:35

1

如果您使用的是API級別8(Android 2.2),那麼您可以通過使用XPath簡化操作。

+0

從來沒有嘗試過be4,生病給它看,謝謝。 – rayman 2011-03-05 12:01:57

+0

當您嘗試執行時,從XML中提取信息很有用,但不用於修改或創建XML。祝你好運! – 2011-03-05 12:08:36

+0

你知道我在哪裏可以找到好的樣本嗎? – rayman 2011-03-05 12:30:19