Tuesday, January 27, 2009

How do I load an org.w3c.dom.Document from XML in a string?

The entire header of this message and it's contents were copied from http://stackoverflow.com/questions/33262/how-do-i-load-an-orgw3cdomdocument-from-xml-in-a-string with one aim: to give higher rank for the page in Google PageRank.

Good reason for this is that good things should be replicated.




I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)

Solution Thanks to Matt McMinn, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.)

  1. public static org.w3c.dom.Document loadXMLFrom(String xml)  
  2.     throws org.xml.sax.SAXException, java.io.IOException {  
  3.     return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes()));  
  4. }  
  5.   
  6. public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)   
  7.     throws org.xml.sax.SAXException, java.io.IOException {  
  8.     javax.xml.parsers.DocumentBuilderFactory factory =  
  9.         javax.xml.parsers.DocumentBuilderFactory.newInstance();  
  10.     factory.setNamespaceAware(true);  
  11.     javax.xml.parsers.DocumentBuilder builder = null;  
  12.     try {  
  13.         builder = factory.newDocumentBuilder();  
  14.     }  
  15.     catch (javax.xml.parsers.ParserConfigurationException ex) {  
  16.     }    
  17.     org.w3c.dom.Document doc = builder.parse(is);  
  18.     is.close();  
  19.     return doc;  
  20. }  

No comments: