Java tutorial
//package com.java2s; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.DocumentBuilder; import org.xml.sax.SAXParseException; import org.xml.sax.SAXException; import org.w3c.dom.Document; public class Main { /** * Parse the XML file and create Document * @param fileName * @return Document */ public static Document parse(InputStream fs) { Document document = null; // Initiate DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // To get a validating parser factory.setValidating(false); // To get one that understands namespaces factory.setNamespaceAware(true); try { // Get DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // Parse and load into memory the Document //document = builder.parse( new File(fileName)); document = builder.parse(fs); return document; } catch (SAXParseException spe) { // Error generated by the parser System.err.println("\n** Parsing error , line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); System.err.println(" " + spe.getMessage()); // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace(); } catch (SAXException sxe) { // Error generated during parsing Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } return null; } }