Press ESC to close

Fast Apex XML Dom Quick Started Guide !

This post explains how to quickly start using the new wrapper Apex API. Developers coding previously on either Ron Hess’s XmlDOM or standard w3c xmldom will feel almost no difference and no learning curve in using this API. As that is the goal of giving this wrapper to be similar to what is existing for too long. This quick start guide provides a few samples only. We will be coming with HTML version of Apex Docs (similar to java docs) soon.

Here is the snippet for quick start

// Used example XML from
String sampleXml = '<bookstore>'   
    + '<book xmlns:c="" category="CHILDREN">'
        + '<!-- Test Comment 1 -->'
	+ '<c:title c:lang="en">Harry Potter</c:title>' 
	+ '<c:author>J K. Rowling</c:author>' 
	+ '<c:year>2005</c:year>'
	+ '<!-- Test Comment 2 -->' 
	+ '<c:price>29.99</c:price>' 
    + '</book>' 
    + '<book xmlns:x="" category="WEB">' 
	+ '<x:title x:lang="en">Learning XML</x:title>' 
	+ '<x:author>Erik T. Ray</x:author>' 
	+ '<x:year>2003</x:year>' 
	+ '<x:price>39.95</x:price>' 
    + '</book>' 
    + '</bookstore>';

TG_XmlDom dom = new TG_XmlDom(sampleXml);
TG_XmlNode root = dom.root;
List<TG_XmlNode> books = root.getElementsByTagName('book');
System.assertEquals(2, books.size());

// Check get attribute
System.assertEquals('CHILDREN', books[0].getAttribute('category'));
System.assertEquals('WEB', books[1].getAttribute('category'));

// Will return the first book element only
TG_XmlNode book = root.getElementByTagName('book');

// Getting node name is handy attribute 
System.assertEquals('book', book.nodeName);

// Easily get the text out of any TG_XmlNode using textContent, you can use the same property to replace the 
// text too 
System.assertEquals('Harry Potter J K. Rowling 2005 29.99', book.textContent);

// To get c:title node inside the first book
TG_XmlNode title = book.getElementByTagName('title');

//Node value is available for getting textNode contents
System.assertEquals('Harry Potter', title.nodeValue);

// toXmlString is available on each node for better debugging assistance
System.assertEquals('<c:title c:lang=\'en\'>Harry Potter</c:title>', title.toXmlString());

// Last child of book node is price
TG_XmlNode lc = book.lastChild;
System.assertEquals('price', lc.nodeName);


Comments (2)

Leave a Reply

%d bloggers like this: