XML, DOM and Xerces

I’ve been having to use the Xerces framework because of school, and after I was rather searching tooo long how to use xerces, I thought I’d just go about and do a little blog on how to use the framework, so that in the future, I still know what I have to do.

Read the rest of the entry for everything

New documents

Parse an existing file


// Create a normal FileInputStream
File f = new File(xmlDatei);
FileInputStream fin = new FileInputStream(f);

// Set the System Property so that the xerces framework knows which class to load
System.setProperty(“javax.xml.parsers.DocumentBuildersFactoryImp”, “org.apache.xerces.jaxp.DocumentBuilderFactoryImpl”);
// Get the instances of the objects with which to work with
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();

// Set some settings
dbFactory.setValidating(true);
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringElementContentWhitespace(false);

// Set an UserErrorHandler
org.xml.sax.ErrorHandler errorHandler = new UserErrorHandler();
docBuilder.setErrorHandler(errorHandler);

// now create a new InputSource instance passing the valid FileInputStream
InputSource inputSrc = new InputSource(fin);
// Now parse the file and save the contents in a Document instance
Document doc = docBuilder.parse(inputSrc);

Create a new Document from scratch


// Set the System Property so that the xerces framework knows which class to load
System.setProperty("javax.xml.parsers.DocumentBuildersFactoryImp", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
// Get the instances of the objects with which to work with
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
DOMImplementation domImpl = docBuilder.getDOMImplementation();
// Create the document with a root element
Document doc = domImpl.createDocument(null, "root", null);

Handling entries


// Add an element
Element root = doc.getDocumentElement();

Element newElem = doc.createElement(“entry”);
newElem.setAttribute(“id”, “_1”);
newElem.setAttribute(“type”, “someType”);
root.appendChild(newElem);

Element nameElem = doc.createElement(“name”);
nameElem.setTextContent(“Some Name);
newElem.appendChild(nameElem);
This would end out with the following xml document:

<root>
<entry id="_1" type="someType">
<name> Some Name
</entry>
</root>