Writing out a DOM subtree to System.out

You can use the XSLT Transformer class to do this.

Here’s an example.

Test.xml

<?xml version="1.0" encoding="UTF-8"?>
<message>
   <content>Hello World!</content>
   <destinations>
      <dest>jmsqueue:myjmsqueue</dest>
      <dest>file:/home/filequeue</dest>
      <dest>123.30.230.90</dest>
   </destinations>
</message>

Main.java:

import org.w3c.dom.*;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
  
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      Document doc;
  
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("test.xml"));
 
         NodeList nodeList = doc.getElementsByTagName("destinations");
         Node node = nodeList.item(0);
  
         // use the XSLT transformation package to output the subtree destinations
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer transformer = tf.newTransformer();
         transformer.transform(new DOMSource(node), new StreamResult(System.out));
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

<?xml version="1.0" encoding="UTF-8"?>
<destinations>
      <dest>jmsqueue:myjmsqueue</dest>
      <dest>file:/home/filequeue</dest>
      <dest>123.30.230.90</dest>
   </destinations>