Cool Penguin

Simple developer guides

Java

More

on CoolPenguin.net:

How to parse XML in Java

This example shows how to create a DOM document tree by reading an XML file

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

class DomReader {
    public static Document parseXmlFile(String filename, boolean validate) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(validate);
            Document doc = factory.newDocumentBuilder().parse(new File(filename));
            return doc;
        } catch (SAXException e) {
            throw new RuntimeException("Parsing error, the XML input is not valid", e);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("Parser error", e);
        } catch (IOException e) {
            throw new RuntimeException("File error", e);
        }
    }
}
No comments posted to this page
Your name

Your comment