Simple construction of an XML Document in Javascript

|

There are basically two options when it comes to constructing XML within Javascript, string concatenation and using the XMLDocument and its methods to construct a "proper" XML document. Depending on need, either is equally valid but it does make life a lot easier further down the line if the XML Document is used. To show the difference, the code below constructs virtually the same XML:


var sXML = '<someEntity id="' + document.getEntityID() + '" userId="' + document.getUserID() +'" />';

function CreateXMLDocument(sRootElementName) { var oXMLDoc = new ActiveXObject('Microsoft.XMLDOM'); var oXMLRoot = oXMLDoc.createElement(sRootElementName); oXMLDoc.documentElement = oXMLRoot; return oXMLDoc; }

oXMLDoc = CreateXMLDocument('someEntity');
oXMLDoc.setAttribute('id', document.getEntityID());
oXMLDoc.setAttribute('userId', document.getUserID());

Yeah, the second one is massively longer - but which is easiest to extend? Plus, if your XML uses a pattern similar to:

<outerBody standardAttribute1="someValue" standardAttribute2="someValue" standardAttribute3="someValue">
<specificEntity attribute1="specificValue1" attribute2="specificValue2" />
<specificEntity attribute1="specificValue1" attribute2="specificValue2" />
</outerBody>

Then you can wrap the creation and completion of all the attributes on the outerBody inside CreateXMLDocument, thus ensuring that for each and every XML document you construct it's always the same. The more complex the XML that the Javascript is building becomes, the quicker the benefit of using the XML DOM and encapsulating the usage of it in custom functions becomes apparent.

About this Entry

This page contains a single entry by Robert Wray published on March 28, 2007 9:00 AM.

Useful Javascript for Select Box population was the previous entry in this blog.

Converting Request.InputStream to a string - Part 2 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.04