DOM API

From GEANT2-JRA1 Wiki

Contents

Creating DOM document from String

String xml = "<aaa><bbb>B1</bbb><bbb>B2</bbb></aaa>";
 InputSource input = new InputSource(new StringReader( xml );

Xerces DOM API

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 DocumentBuilder db = dbf.newDocumentBuilder();
 Document doc = db.parse( input );

jDOM

SAXBuilder builder = new SAXBuilder();
 Document doc = builder.build( input );

Serializing DOM document (write)

Xerces DOM API

OutputFormat format = new OutputFormat( doc );
 StringWriter stringOut = new StringWriter();
 
 XMLSerializer serial = new XMLSerializer( stringOut, format );
 serial.asDOMSerializer();
 serial.serialize( doc.getDocumentElement() );
 
 System.out.println( stringOut.toString() );

jDOM

XMLOutputter outp = new XMLOutputter();
 OutputStream ostream = System.out;
 outp.output(doc, ostream);

Load from file

Xerces

DocumentBuilderFactory factory = 
   DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
      
 Document document = builder.parse(filename);

or:

DOMParser parser = new DOMParser();
 parser.parse(filename);
 Document document = parser.getDocument();

jDOM

org.jdom.input.SAXBuilder parser = new org.jdom.input.SAXBuilder();
 org.jdom.Document doc = parser.build(filename);

XPath

Xerces

  • Perform XPath expression on DOM (Document doc)
String xpathQuery = "/nmwg:message"; //XPath expression
 
 Transformer serializer = TransformerFactory.newInstance().newTransformer();
 serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        
 // Create an XPath evaluator and pass in the document.
 XPathEvaluator evaluator = new XPathEvaluatorImpl(doc);
 XPathNSResolver resolver = evaluator.createNSResolver(doc);
        
 // Evaluate the xpath expression
 XPathResult result = (XPathResult) evaluator.evaluate(
                    xpathQuery,
                    doc,
                    resolver,
                    XPathResult.UNORDERED_NODE_ITERATOR_TYPE,
                    null
                    );
  • Serialize the found nodes, store result in results as vector of Strings
Node n;
 while ((n = result.iterateNext())!= null) {
                
   StringBuffer outputBuffer = new StringBuffer();
                
   OutputStream outputStream = 
       new StringBufferOutputStream(outputBuffer);                
   try {
                        
       serializer.transform(
       new DOMSource(n), new StreamResult(
           new OutputStreamWriter(outputStream)));
       results.add(outputBuffer.toString());
                        
   } catch (TransformerException e) {
       e.printStackTrace();
   }
  • results are in results, may be converted into array if needed
String[] stringResults = new String[results.size()];
   results.toArray(stringResults);
Personal tools