Java tutorial
//package com.java2s; import java.io.File; 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.xml.sax.SAXException; public class Main { private static DocumentBuilderFactory documentBuilderFactory; private static DocumentBuilder documentBuilder; public static int countChildNodes(String fileName) { Document doc = parseFile(fileName); return doc.getFirstChild().getChildNodes().getLength(); } public static Document parseFile(String fileName) { System.out.println("Parsing XML file... " + fileName); if (documentBuilder == null) { refreshDocumentBuilder(); } File sourceFile = new File(fileName); try { return documentBuilder.parse(sourceFile); } catch (SAXException e) { System.out.println("Wrong XML file structure: " + e.getMessage()); return null; } catch (IOException e) { System.out.println("Could not read source file: " + e.getMessage()); } return null; } public static void refreshDocumentBuilder() { if (documentBuilderFactory == null) { refreshDocumentBuilderFactory(); } try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { System.out.println("Wrong parser configuration: " + e.getMessage()); } } public static void refreshDocumentBuilderFactory() { documentBuilderFactory = DocumentBuilderFactory.newInstance(); } }