Google Wetter XML (nur current_condition) auslesen mit Java

ndrizza

Mitglied
Hallo zusammen,

ich probiere seit 1 Tag diese XML Datei mit Java auszulesen:

[XML]<?xml version="1.0"?>
<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="Zürich District, Canton of Zürich"/>
<postal_code data="Zuerich"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2011-01-12"/>
<current_date_time data="2011-01-12 17:20:00 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Light rain"/>
<temp_f data="43"/>
<temp_c data="6"/>
<humidity data="Humidity: 81%"/>
<icon data="/ig/images/weather/mist.gif"/>
<wind_condition data="Wind: S at 9 mph"/>
</current_conditions>
<forecast_conditions>
<day_of_week data="Wed"/>
<low data="41"/>
<high data="46"/>
<icon data="/ig/images/weather/chance_of_rain.gif"/>
<condition data="Chance of Rain"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="Thu"/>
<low data="41"/>
<high data="51"/>
<icon data="/ig/images/weather/chance_of_rain.gif"/>
<condition data="Chance of Rain"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="Fri"/>
<low data="39"/>
<high data="48"/>
<icon data="/ig/images/weather/sunny.gif"/>
<condition data="Clear"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="Sat"/>
<low data="39"/>
<high data="50"/>
<icon data="/ig/images/weather/chance_of_rain.gif"/>
<condition data="Chance of Rain"/>
</forecast_conditions>
</weather>
</xml_api_reply>
[/XML]



mit diesem .java File probiere ich es sie auszulesen, aber es klappt nicht:
(Das File beinhaltet mehrere Versuche an den roten Wert als String zu kommen)

Java:
package Weather;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader2 {

 public static void main(String argv[]) {

  try {
  File file = new File("MyXMLFile2.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  
  System.out.println(doc.getDocumentElement().getNodeName());
  NodeList n = doc.getDocumentElement().getChildNodes();
  System.out.println(n.item(0).getNodeName());
  
  System.out.println("Title: " + doc.getDocumentElement().getNodeName());
  String b = doc.getDocumentElement().getChildNodes().item(0).getNodeName();
  System.out.println(b);
  
  NodeList nl1 = doc.getElementsByTagName("current_conditions");
  Element firstelement = (Element) nl1.item(0);
  NodeList nl11 = firstelement.getChildNodes();
  System.out.println(firstelement.getNodeName());
  System.out.println(((Node) nl11.item(0)).getNodeName());



  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}

Ich möchte nur den rot markierten Wert aus dem XML auslesen. Der Rest ist für mein Programm nicht wichtig.
Wäre sehr froh um Hilfe!

Gruss
 

ndrizza

Mitglied
Ich habs probiert mit element, aber irgendwie funktioniert es nicht, könntet ihr mir weiterhelfen? (Abfragebefehl ist im Code markiert)

Java:
package Weather;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader2 {

 public static void main(String argv[]) {

  try {
  File file = new File("MyXMLFile.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  
  // ab hier Befehl zum Abfragen
  NodeList nl1 = (NodeList) doc.getElementsByTagName("current_conditions");
  NodeList nl2 = (NodeList) nl1.item(0).getChildNodes();
  Element firstelement = (Element) nl2.item(0);
  String value = firstelement.getAttribute("condition data");
  // Ende Befehl abfragen
  
  System.out.println(value);


  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}

Vielen Dank für Eure Beiträge

Gruss
 

Noctarius

Top Contributor
Das Attribute heißt auch nicht "condition data" sondern nur "data".

PS: Sich darauf zu verlassen, dass "condition" immer das erste Child-Element ist, würde ich lassen. Die Reihenfolge ist in XML nicht definiert. Besser ist es alle Child-Elemente durchzugehen und zu schauen ob [c]getLocalName()[/c] den gewünschten Wert liefert.
Java:
final NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
  Node child = children.item(i);

  if (child.getNodeType() != Node.ELEMENT_NODE)
    continue;

  if (!"condition".equals(child.getLocalName()))
    continue;

  String data = ((Element) child).getAttribute("data");
  ...
}
 
Zuletzt bearbeitet:

ndrizza

Mitglied
Hallo,

ich habe jetzt den Code wie beschrieben geändert, aber er liefert keinen String in der Console.
Könnte mir bitte jemand einen kompletten funktionierenden Code posten?

Java:
package Weather;
 
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class XMLReader3 {
 
 public static void main(String argv[]) {
 
  try {
  File file = new File("MyXMLFile.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  
  NodeList nl1 = (NodeList) doc.getElementsByTagName("current_conditions");

  for (int i = 0; i < nl1.getLength(); i++) {
	  Node child = nl1.item(i);
	  if (child.getNodeType() != Node.ELEMENT_NODE)
	    continue;
	  if (!"condition".equals(child.getLocalName()))
	    continue;
	  String data = ((Element) child).getAttribute("data");
	  System.out.println(data);
	}
  
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}

Gruss
 

Noctarius

Top Contributor
Java:
package Weather;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader3 {

	public static void main(String argv[]) {

		try {
			File file = new File("MyXMLFile.xml");
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();

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

			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);

				if (node.getNodeType() != Node.ELEMENT_NODE)
					continue;

				NodeList children = nodes.getChildNodes();

				for (int o = 0; o < children.getLength(); o++) {
					Node child = children.item(o);
					if (child.getNodeType() != Node.ELEMENT_NODE)
						continue;

					if (!"condition".equals(child.getLocalName()))
						continue;

					String data = ((Element) child).getAttribute("data");
					System.out.println(data);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Zuletzt bearbeitet:

ndrizza

Mitglied
vielen dank für den code, aber er geht irgendwie nicht:

Es kommt folgende Fehlermeldung.
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl cannot be cast to org.w3c.dom.Element
at Weather.XMLReader3.main(XMLReader3.java:31)

Weiss jemand wo das problem liegt? (Ev. müsste man das XML File nochmals anschauen - aber ich weiss nicht wo der Fehler liegen kann)

Gruss Andreas.

http://www.google.com/ig/api?weather=Zuerich
 
Zuletzt bearbeitet:

ndrizza

Mitglied
Habe inzwischen eine ziemlich kreative Lösung gefunden:) Ist nicht wirklich professionell, aber es funktioniert:)

Java:
    System.out.println("Root element :" + doc.getDocumentElement().getChildNodes().item(1).getChildNodes().item(3).getChildNodes().item(1).getAttributes().getNamedItem("data"));

Ich bin jederzeit froh um weitere Ratschläge von euch! Vielen Dank!

Ev. hilft euch mein komischer Befehl weiter das XML zu verstehen.:)

Gruss Andreas
 

Heady86

Bekanntes Mitglied
Wenn ich oben Zeile 30 und 37 ein bischen was änder dann gehts bei mir..

Java:
...
NodeList children = nodes.item(0).getChildNodes();
	 
  for (int o = 0; o < children.getLength(); o++) {
   Node child = children.item(o);
   if (child.getNodeType() != Node.ELEMENT_NODE)
       continue;
   if (!"condition".equals(child.getNodeName()))
       continue;
	 
   String data = ((Element) child).getAttribute("data");
   System.out.println(data);
}
...
 

ndrizza

Mitglied
vielen Dank für eure Hilfe! Hier noch das ganze komplett für alle die daran interessiert sind! Vielen Dank! Grüsse

Java:
package Weather;
 
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class XMLReader3 {
 
    public static void main(String argv[]) {
 
        try {
            File file = new File("wetter.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
 
            NodeList nodes = (NodeList) doc
                    .getElementsByTagName("current_conditions");
 
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
 
                if (node.getNodeType() != Node.ELEMENT_NODE)
                    continue;
 

                    NodeList children = nodes.item(0).getChildNodes();
                    
                    for (int o = 0; o < children.getLength(); o++) {
                     Node child = children.item(o);
                     if (child.getNodeType() != Node.ELEMENT_NODE)
                         continue;
                     if (!"condition".equals(child.getNodeName()))
                         continue;
                       
                     String data = ((Element) child).getAttribute("data");
                     System.out.println(data);

                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Zuletzt bearbeitet:

FArt

Top Contributor
Ich hätte als Lösung XPath verwendet. Goolge mal nach "java" und "xpath" und benutze für dein XML folgenden, eindeutigen XPath: /xml_api_reply/weather/current_conditions/condition/@data

... fertig...
 

Ähnliche Java Themen

Neue Themen


Oben