XML: where -Abfragen wie bei sql?!

X

XXXKF

Gast
Hallo Java-Forum!

ich hoffe das Thema gibt es noch nicht, aber auf Anhieb hab ich nichts passendes zu meiner Frage gefunden.

Ich habe folgendes XML-File:
[XML]
<results count="27">

<result>
<id>1</id>
<name>A.T. Kearney GmbH</name>
<kategorie>Wirtschaftswissenschaften </kategorie>
<tag>Donnerstag</tag>
<standnummer>12</standnummer>
<branche>Strategische Unternehmungsberatung</branche>
</result>

<result>
<id>2 </id>
<name>BASF SE </name>
<kategorie>Naturwissenschaften </kategorie>
<tag>Dienstag </tag>
<standnummer>15 </standnummer>
<branche>Chemie </branche>

</result>

<result>
<id>3 </id>
<name>Carl Zeiss AG </name>
<kategorie>Geisteswissenschaften </kategorie>
<tag>Donnerstag </tag>
<standnummer>27 </standnummer>
<branche>Feinmechanik und Optik </branche>
</result>

<result>
<id>4</id>
<name>Daimler AG</name>
<kategorie>Elektrotechnik</kategorie>
<tag>Donnerstag</tag>
<standnummer>37</standnummer>
<branche>Automobilindustrie </branche>
</result>
[/XML]
... usw.
Ich würde gern eine Liste mit Firmen die am Donnerstag da sind erstellen.
Bisher hab ich nur eine Liste mit allen FIrmen, aber die würde ich gerne ordnen. Soll eine Android App werden.
Gibt es sowas wie eine "Gib nur die Firmen aus, die den Tag <tag>Donnerstag</tag> besitzen aus"-Abfrage????
kann man sowas mit XML Dateien realisieren?
Ich hoffe man versteht mein Anliegen, bin noch eine ziemliche Anfängerin in dem Gebiet.

Danke schon mal im Voraus :)

Grüßle
XXX
 
Zuletzt bearbeitet von einem Moderator:

Noctarius

Top Contributor
Ich würde alle Firmen mit einem XPath Ausdruck abrufen und überprüfen ob der Tag Donnerstag ist, wenn ja in die Ergebnisliste kopieren.
 
X

XXXKF

Gast
Puh, ok! Danke für die schnelle Antwort. Da muss ich mich erst mal reinlesen.
Hab meine XML bisher mit DOM abgefragt.
 
X

XXXKF

Gast
Danke Basti, das schaut recht verständlich aus...Jedoch hab wirklich noch keine Ahnung wie das mit XPath funktionieren soll.
Zumindest weiß ich gerade nicht wo ich das einsetzen soll ^^
 

eRaaaa

Top Contributor
Ich bin ja mal nicht so, hier ein Beispiel basierend auf deiner XML-Datei(hier firmen.xml) und den Standartpackages javax.xml und org.w3c.dom

Java:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

//......

		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse("firmen.xml");
		XPathExpression expr = XPathFactory.newInstance().newXPath().compile("/results/result[contains(tag,'Donnerstag')]");
		NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < nodes.getLength(); i++) {
			NodeList n = nodes.item(i).getChildNodes();
			for (int j = 0; j < n.getLength(); j++) {
				System.out.println(n.item(j).getTextContent().trim());
			}
			System.out.println("---------");
		}

Sollte dir die Firmen 1,3 und 4 liefern!
 
X

XXXKF

Gast
Oh man ich bin einfach zu dämlich für das Ganze.
Ich checks grad absolut nicht..wie ich das in meinen Code einbauen soll. Obwohl das gerade nicht so schwer sein sollte.

Hier mal meine Datei mit der die XML ausm Netz geparst wird:
Java:
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions {

	public final static Document XMLfromString(String xml){
		
		Document doc = null;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
        	
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(xml));
	        doc = db.parse(is); 
	        
		} catch (ParserConfigurationException e) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
		} catch (IOException e) {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}
		       
        return doc;
        
	}
	
	/** Returns element value
	  * @param elem element (it is XML tag)
	  * @return Element value otherwise empty String
	  */
	 public final static String getElementValue( Node elem ) {
	     Node kid;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
	                 if( kid.getNodeType() == Node.TEXT_NODE  ){
	                     return kid.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }
		 
	 public static String getXML(){	 
			String line = null;

			try {
				
				DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(
					"http://www.fo-in.de/resttest/ausstellerikommaster.xml");

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				line = EntityUtils.toString(httpEntity);
				
			} catch (UnsupportedEncodingException e) {
				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
			} catch (MalformedURLException e) {
				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
			} catch (IOException e) {
				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
			}

			return line;

	}
	 
	public static int numResults(Document doc){		
		Node results = doc.getDocumentElement();
		int res = -1;
		
		try{
			res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
		}catch(Exception e ){
			res = -1;
		}
		
		return res;
	}

	public static String getValue(Element item, String str) {		
		NodeList n = item.getElementsByTagName(str);		
		return XMLfunctions.getElementValue(n.item(0)); //n.item(0)
	}

}

Und hier die *.java in der ich die Tags in eine Liste übergeb.
Java:
public class MittwochTab extends ListActivity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listplaceholder);

		ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

		String xml = XMLfunctions.getXML();
		Document doc = XMLfunctions.XMLfromString(xml);

		int numResults = XMLfunctions.numResults(doc);

		if ((numResults <= 0)) {
			Toast.makeText(MittwochTab.this, "Keine Ergebnisse", Toast.LENGTH_LONG)
					.show();
			finish();
		}

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

		for (int i = 0; i < nodes.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nodes.item(i);
			map.put("id", XMLfunctions.getValue(e, "id"));
			map.put("name", "" + XMLfunctions.getValue(e, "name"));
			map.put("kategorie",
					"Kategorie: " + XMLfunctions.getValue(e, "kategorie"));
			map.put("tag", "Tag: " + XMLfunctions.getValue(e, "tag"));
			map.put("Standnummer",
					"Standnummer: " + XMLfunctions.getValue(e, "standnummer"));
			map.put("branche",
					"Branche: " + XMLfunctions.getValue(e, "branche"));
			map.put("mitarbeiter",
					"Mitarbeiter: " + XMLfunctions.getValue(e, "mitarbeiter"));
			map.put("praktikum",
					"Praktikum: " + XMLfunctions.getValue(e, "praktikum"));
			map.put("abschlussarbeit",
					"Abschlussarbeit: "
							+ XMLfunctions.getValue(e, "abschlussarbeit"));
			map.put("internet",
					"Internet: " + XMLfunctions.getValue(e, "internet"));
			map.put("telefon",
					"Telefon: " + XMLfunctions.getValue(e, "telefon"));
			map.put("strasse", "Straße: " + XMLfunctions.getValue(e, "strasse"));
			map.put("postleitzahl",
					"Postleitzahl: " + XMLfunctions.getValue(e, "postleitzahl"));
			map.put("stadt", "Stadt: " + XMLfunctions.getValue(e, "stadt"));
			map.put("email", "EMail: " + XMLfunctions.getValue(e, "email"));

			mylist.add(map);
		}

		ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.listxml,
				new String[] { "name", "Standnummer", "tag" }, new int[] {
						R.id.item_title, R.id.item_subtitle });

		setListAdapter(adapter);

		// Get the listView ( from: ListActivity ) und set OnItemClickListener für Dialogfenster
		final ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
	
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				@SuppressWarnings("unchecked")
				final HashMap<String, String> o = (HashMap<String, String>) lv
						.getItemAtPosition(position);
			

				AlertDialog.Builder adb = new AlertDialog.Builder(MittwochTab.this);
				adb.setTitle("Wo willst Du hin?");

				adb.setCancelable(false);
				adb.setPositiveButton("zum Standplan",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Intent iPlan = new Intent(MittwochTab.this,
										Impressum.class);
								iPlan.putExtra("item", o);
								startActivity(iPlan);
							}
						});

				adb.setNegativeButton("zum Firmenprofil",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Intent iProfil = new Intent(MittwochTab.this,
										Firmenprofil.class);
								iProfil.putExtra("item", o);
								// iFahrzeug_new.putExtra("pos", position);
								startActivity(iProfil);
							}
						});
				adb.setNeutralButton("zurück",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

				adb.show();
				// End Dialog Window

			}
		});

	}
}



Das wäre jetzt meine Liste mit ALLEN Firmen..
 
Ähnliche Java Themen

Ähnliche Java Themen

Neue Themen


Oben