Skip to content

Instantly share code, notes, and snippets.

@samisnotinsane
Created April 10, 2018 23:19
Show Gist options
  • Save samisnotinsane/6ff3fa3add604dd9587143442b055a63 to your computer and use it in GitHub Desktop.
Save samisnotinsane/6ff3fa3add604dd9587143442b055a63 to your computer and use it in GitHub Desktop.
Creating a DOM tree from scratch using Java DOM API.
import java.util.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class DocumentTreeExample {
public static void main(String[] args) throws DOMException {
System.out.println("Initialising DOM tree...");
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
System.out.println("Tree ready.");
// create the root element node
Element element = doc.createElement("root");
doc.appendChild(element);
// add element after the first child of the root element
Element itemElement = doc.createElement("item");
element.appendChild(itemElement);
// add an attribute to the node
itemElement.setAttribute("attrkey", "attrvalue");
if(doc == null)
System.err.println("doc is NULL!");
else
System.out.println("doc is NOT NULL");
System.out.println(doc); // out: [#document: null]
System.out.println(doc.getDocumentElement().getTextContent()); // out: (doesn't print anything)
} catch (ParserConfigurationException e) {
System.err.println(e);
}
System.out.println("---\nTerminated");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment