jdom & elemente zählen

Tin80

Grünschnabel
Hallo zusammen

Ich möchte gerne in einem XML-File zählen wieviele Elemente eines bestimmten Typ es gibt.
Hier ein Auszug aus meinem XML, damit die Frage etwas klarer wird:

Code:
<class name="Win32_NetworkAdapterConfiguration">
  <method name="EnableStatic" param="123.325.35.26"/>
  <method name="SetGatways" param="123.35.26.35"/>
  <restriction text="Error..."/>
</class>

Nun möchte ich zählen, wie oft das Element "method" in class vorkommt. Weiss jemand wie das geht?

Vielen Dank für eure Hilfe.

Gruss
Tin
 
Hallo!

Schau mal hier:
Code:
<?xml version="1.0"?>
<class name="Win32_NetworkAdapterConfiguration">
	<method name="EnableStatic" param="123.325.35.26"/>
	<method name="SetGatways" param="123.35.26.35"/>
	<restriction text="Error..."/>
</class>

Code:
/**
 * 
 */
package de.tutorials;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author Administrator
 * 
 */
public class XMLElementCounter {

	private int cnt;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		new XMLElementCounter().doIt();
	}

	private void doIt() throws Exception {
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

		parser.parse(XMLElementCounter.class.getResourceAsStream("foo.xml"),
				new DefaultHandler() {
					public void startElement(String uri, String localName,
							String qName, Attributes attributes) {
						if (qName.equals("method")) {
							cnt++;
						}
					}
				});

		System.out.println(cnt);
	}
}

... oder Java 5 Mittel und XPath einsetzen:
Code:
/**
 * 
 */
package de.tutorials;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

/**
 * @author Administrator
 * 
 */
public class XMLElementCounter {
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		new XMLElementCounter().doIt();
	}

	private void doIt() throws Exception {
		System.out.println(XPathFactory.newInstance().newXPath().evaluate(
				"count(//method)",
				new InputSource(XMLElementCounter.class
						.getResourceAsStream("foo.xml"))));

	}
}

Gruß Tom
 
Hallo

Danke. Ich habe mittlerweile eine einfachere Lösung gefunden:

Code:
Element root = doc.getRootElement();
Element cimclass = root.getChild("cimclass");
List methods = cimclass.getChildren("method"); 
int countMethods = methods.size();

Danke trotzdem.
Gruss Tin
 
Zurück