XPath: Alle Kinder in einer Schleife auslesen

Cyborg

Aktives Mitglied
Guten Abend,

ich tüftel gerade wie ich mit XPath vernünftig an meine XML Elemente ran komme.

XML:
Code:
<products>

  <product>
    <id>1</id>
    <name>1</name>
    <price>1</price>
  </product>

  <product>
    <id>2</id>
    <name>2</name>
    <price>2</price>
  </product>

  ...

</products>

Mit folgendem Code:

Code:
String expression = "/products/product/name";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
   System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}

komme ich immer an den Namen.
Ich würde gern in einer Schleife gleichzeitig an id, name und price rankommen.

Also ungefähr so:

Code:
expression = "/products/product";
...
nodeList.item(i).getNode("id").getNodeValue()
nodeList.item(i).getNode("name").getNodeValue()
nodeList.item(i).getNode("price").getNodeValue()

Klappt das irgendwie?

// EDIT:

Habe bei Google noch etwas gefunden

Code:
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
   String id = xPath.evaluate("id", nodeList.item(i));
   String name = xPath.evaluate("name", nodeList.item(i));
   String price = xPath.evaluate("price", nodeList.item(i));
}

Allerdings brauch das bei ca 2300 Einträgen knapp 30 Sekunden :O
Ist das richtig, dass das so lange brauch?
 
Zuletzt bearbeitet:
Hi,
Wie wärs so:
Java:
public void readXmlFile(String xmlFile) {
	try {
		FileInputStream file = new FileInputStream(new File(xmlFile));
        
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
         
        DocumentBuilder builder =  builderFactory.newDocumentBuilder();
         
        Document xmlDocument = builder.parse(file);
		
		XPath xPath =  XPathFactory.newInstance().newXPath();

		String expression = "/products/product";

		NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
					
		for (int i = 0; i < nodeList.getLength(); i++) {
			NodeList childList = nodeList.item(i).getChildNodes();
			for (int j = 0; j < childList.getLength(); j++) {
				NodeList childChildList = childList.item(j).getChildNodes();
				for (int k = 0; k < childChildList.getLength(); k++) {
					Node child = childChildList.item(k);
					System.out.println(childList.item(j).getNodeName() + ": " + child.getNodeValue());
				}
			}
		}
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }  
   
}
 

Zurück
Oben