How to create a XML document

Create a XML documentA newly created, in-memory, XML document is sometimes necessary for ad-hoc data manipulation and / or document generation.

Examples of common use-cases are:

  • Populate a document for integration (prior to dispatch)
  • Populate a document with data to save to disc or database
  • Create a temporary document for data manipulation and / or processing.

The purpose of this example is to show you how to create a new XML document object in memory. Bear in mind that XML DOM objects in memory can have an impact on available resources and system performance if you are using them to store and / or process LARGE datasets.


Java

The example does the following in order:

  1. Retrieve an instance of a document builder factory
  2. Set the validating and namespace aware flags on the factory. Defaults are false. If the intention is to validate your document then a DTD needs to be specified as well.
  3. Create a new document builder from the factory.
  4. Create a new XML document with no root element – only the standard declaration.
  5. Create and append a new element node to the document. The first child element appended to a document is the root element.
public static Document createDocument(String rootName, boolean validating, boolean namespaceaware) throws ParserConfigurationException {
Document xmlDoc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
factory.setNamespaceAware(namespaceaware);
DocumentBuilder builder = factory.newDocumentBuilder();
xmlDoc = builder.newDocument();
xmlDoc.appendChild(xmlDoc.createElement(rootName));
return xmlDoc;
}

Note: A validating document will require knowledge of the DTD associated with your document. If the document must have a specific schema, then the new document builder must be namespace-aware.

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