Friday, March 30, 2007

I had a requirement where I had to convert a XML String Message to a DOM Document Object. The DOM Document Object would later be traversed to retrieve important XMl Elements.

I spent a good deal of time brushing up on Core Java, JAXP, Java I/O, etc - & of course, a lot of Googling. Finally, I reached enlightnement - here's the code snippet that worked for me :-


DocumentBuilderFactory objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
Document objDocument = objDocumentBuilder.parse
(
new ByteArrayInputStream
(
( "< Person >" +
"< Name >Sandy< / Name >" +
"< FirstName >Sandeep< / FirstName >" +

"< / Person >" ).getBytes()
)
);

I had to feed the String to a ByteArrayInputStream & pass it to the DocumentBuilder to parse & spew out the Document Object.