DOM - Bedingte Ausgabe

jokibär

Mitglied
Hallo,

ich habe gestern einen ganzen Tag erfolglos damit vergeutet, eine bedingte Ausgabe für die jeweiligen XML-Knoten meines XML-Dokuments auszugeben.

Das Dokument sieht folgendermaßen aus:

[XML]
<?xml version="1.0"?>
<travel>
<option>
<country>France</country>
<location>Brest</location>
<terrain>seaside</terrain>
<cost_travel>low</cost_travel>
<cost_accomodation>medium</cost_accomodation>
</option>
</travel>

usw...
[/XML]

Ich möchte nur die Knoten ausgeben, bei denen z.B. Attribute country equals "Germany", terrain equals "seaside", cost_travel equals "low" und cost_accomodation equals "medium" == true. Attribut location wäre damit ermittelt und soll ebenfalls mit ausgegeben werden. Quasy ein query a la
SQL:
select country, location, terrain, cost_travel, cost_accomodation 
from option
where
country='Germany' AND
terrain='seaside' AND
cost_travel='low' AND
cost_accomodation='medium';

Ich hab ersthaft viel probiert und gegoogelt aber ich habe wirklich nichts entsprechendes gefunden, das hat mich fast wahnsinnig gemacht. Das kann doch nicht so schwierig sein?!

Könnte mir bitte jemand ein funktionierendes Beispiel geben, am besten mit DOM? Ich wäre sehr dankbar!

Viele Grüße

Jokibär

P.S. Ich hatte eine Methode gefunden und angepaßt, aber hier kann ich nur einen Wert angeben:
Java:
 public void readXML(String pCountry, String pTerrain, String pCostofTraveling,String pAccomodationCost) {
        
        
        /*Result set of each option concatenated to one String-object*/
	  try {
 
		File fXmlFile = new File("traveldata.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
 
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("option");
		System.out.println("-----------------------");
 
		for (int temp = 0; temp < nList.getLength(); temp++) {
 
		   Node nNode = nList.item(temp);
		   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
		   Element eElement = (Element) nNode;
                   NodeList countryLst = eElement.getElementsByTagName("country");
                   Element countryElmnt = (Element) countryLst.item(0);
                   NodeList country = countryElmnt.getChildNodes();
                                   
                   NodeList terrainLst = eElement.getElementsByTagName("terrain");
                   Element terrainElmnt = (Element) terrainLst.item(0);
                   NodeList terrain = terrainElmnt.getChildNodes();
               
                   if(pTerrain.equalsIgnoreCase (((Node) terrain.item(0)).getNodeValue()) && pCountry.equalsIgnoreCase (((Node) country.item(0)).getNodeValue()))    
                   System.out.println("country "  + ((Node) country.item(0)).getNodeValue());
                   System.out.println("terrain "  + ((Node) terrain.item(0)).getNodeValue());
		   }
		}
	  } catch (Exception e) {
		e.printStackTrace();
                System.out.print(e);
	  }
  }
 
N

nillehammer

Gast
Dafür gibts die XML-Abfragesprache XQuery. Ich habe selbst damit keine Erfahrungen, deswegen kann ich Dich nur auf folgende Seite verweisen, die sehr gute XML-Tutorials enthält: XQuery Tutorial
 

eRaaaa

Top Contributor
Ansonsten ginge das wohl auch mit XPath.
"//option[country='Germany' and terrain='seaside' and cost_travel='low' and cost_accomodation='medium']"
Solltest du aber viele verschiedene Abfragen machen wollen, wäre XQuery in der Tat evtl. sinnvoller :oops:
Ein Beispiel mit XPath
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.Node;
import org.w3c.dom.NodeList;

//......

	public static void main(String[] args) throws Exception {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document document = builder.parse("traveldata.xml");
		XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//option[country='Germany' and terrain='seaside' and cost_travel='low' and cost_accomodation='medium']");
		NodeList nodes = (NodeList) expr.evaluate(document,XPathConstants.NODESET);
		for (int i = 0; i < nodes.getLength(); i++) {
			NodeList n = nodes.item(i).getChildNodes();
			for (int j = 0; j < n.getLength(); j++) {
				Node node = n.item(j);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					System.out.println(node.getNodeName()+" = "+node.getTextContent().trim());
				}
			}
			System.out.println("-----");
		}
	}
 
Zuletzt bearbeitet:

Ähnliche Java Themen

Neue Themen


Oben