XML Tutorials - Herong's Tutorial Examples - v5.25, by Herong Yang
DOMBrowser.java - DOM Interface Java Example
This section provides a tutorial example on how to parse an XML file and print it back in a tree format using DOM interface in Java - JDK 1.8.
The following Java program illustrates how an XML file can be parsed into a DOM document tree, and how "get" methods of Node interface can be used to browse the tree:
/* DOMBrowser.java * Copyright (c) 2002-2018 HerongYang.com. All Rights Reserved. */ import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; class DOMBrowser { public static void main(String[] args) { try { File x = new File(args[0]); DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder b = f.newDocumentBuilder(); Document d = b.parse(x); printNode(d, ""); } catch (ParserConfigurationException e) { System.out.println(e.toString()); } catch (SAXException e) { System.out.println(e.toString()); } catch (IOException e) { System.out.println(e.toString()); } } static void printNode(Node n, String p) { NodeList l = n.getChildNodes(); NamedNodeMap m = n.getAttributes(); int ml = -1; if (m!=null) ml = m.getLength(); System.out.println(p+n.getNodeName()+": "+n.getNodeType()+", " +l.getLength()+", "+ml+", "+n.getNodeValue()); for (int i=0; i<ml; i++) { Node c = m.item(i); printNode(c,p+" |-"); } for (int i=0; i<l.getLength(); i++) { Node c = l.item(i); printNode(c,p+" "); } } }
Now let's use this program to browse my first XML file, hello.xml:
<?xml version="1.0"?> <p>Hello world!</p>
You will get the following output with JDK 10 and 1.8:
herong> java DOMBrowser hello.xml #document: 9, 1, -1, null p: 1, 1, 0, null #text: 3, 0, -1, Hello world!
Here is how to read the output:
Table of Contents
Introduction of XML (eXtensible Markup Language)
►DOM (Document Object Model) Programming Interface
What Is DOM (Document Object Model)
Using DOM Implementation Provided in JDK
DOM Specifications and DOM Node Interface
►DOMBrowser.java - DOM Interface Java Example
Building a New DOM Document Object
Converting DOM Document Objects to XML Files
SAX (Simple API for XML) Programming Interface
DTD (Document Type Definition) Introduction
Validating an XML Document against the Specified DTD Document Type
XSD (XML Schema Definition) Introduction
Validating XML Documents Against Specified XML Schemas
XSL (Extensible Stylesheet Language) Introduction
XSLT (XSL Transformations) Introduction
XSLT Elements as Programming Statements
Control and Generate XML Element in the Result
PHP Extensions for XML Manipulation
Processing XML with Python Scripts
XML Tools Plugin for Notepad++
XML Plugin Packages for Atom Editor