Wie man XML-Elemente in Java zählt - (DOM Parser)
In diesem Beispiel zeigen wir Ihnen, wie Sie mitDOM Parser die Gesamtzahl der Elemente in einer XML-Datei zählen. Suchen Sie zuerst nach dem Elementnamen, und verwenden Sie dannNodeList.getLength()
, um die Gesamtzahl der verfügbaren Elemente abzurufen.
NodeList list = doc.getElementsByTagName("staff"); System.out.println("Total of elements : " + list.getLength());
Datei: file.xml
yong mook kim example 2000000 29 low yin fong fong fong 1000000 Ali Baba Alibaba 199000 40
File : CountXMLElement.java - Durchsucht die Gesamtzahl der verfügbaren "staff" -Elemente.
import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class CountXMLElement { public static void main(String argv[]) { try { String filepath = "c:\\file.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); NodeList list = doc.getElementsByTagName("staff"); System.out.println("Total of elements : " + list.getLength()); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } } }
Ausgabe
Total of elements : 3