How to read an XML document

data-readReading / Opening an XML document is an essential skill for XML processing. The method of reading an XML document depends on the technical requirements (document source, code purpose, etc.) and constraints (processing speed, memory footprint, etc.).

Reading an XML document from a stream source is the most basic scenario when loading an XML document – Any operation where a source XML document is expressed as a string, file, network or some other resource can be opened as a stream.


Java

The Java example below will attempt to load an XML document into memory using the default XML parser configured for the JVM.

import java.io.InputStream;
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;
/**
 * Reads an XML document from an InputStream. 
 * 
 * The method parses the content from the given InputStream and returns a DOM object.
 * 
 * @param in The XML document content expressed as an input stream.
 * @param validating Specifies that the parser produced by this code will validate documents as they are parsed.
 * @param namespaceaware Specifies that the parser produced by this code will provide support for XML namespaces. 
 * @return an XML document if successfully loaded.
 * @throws SAXException thrown  If any parse errors occur. 
 * @throws ParserConfigurationException  if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException If any IO errors occur. 
 */
public static Document readDocument(InputStream in, boolean validating, boolean namespaceaware) throws SAXException, ParserConfigurationException, IOException {
    Document xmlDoc = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validating);
    factory.setNamespaceAware(namespaceaware);
    DocumentBuilder builder = factory.newDocumentBuilder();
    xmlDoc = builder.parse(in);
    return xmlDoc;
}

 

C#

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Visual Basic

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Posted in XML and tagged , .

Leave a Reply