XML
Beginner
2 min read
XML Parsing in Java: DOM and SAX
Example
// Java: DOM parsing with DocumentBuilder
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
public class DomParserExample {
static final String XML = """
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="b001" category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
<price>12.99</price>
</book>
<book id="b002" category="non-fiction">
<title>Clean Code</title>
<author>Robert C. Martin</author>
<year>2008</year>
<price>35.00</price>
</book>
</library>""";
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
// Disable XXE for security
factory.setFeature(
"http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder builder = factory.newDocumentBuilder();
byte[] bytes = XML.getBytes(StandardCharsets.UTF_8);
Document doc = builder.parse(new ByteArrayInputStream(bytes));
NodeList books = doc.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
Element book = (Element) books.item(i);
String id = book.getAttribute("id");
String category = book.getAttribute("category");
String title = book.getElementsByTagName("title")
.item(0).getTextContent();
String author = book.getElementsByTagName("author")
.item(0).getTextContent();
System.out.printf("[%s] %s by %s (%s)%n",
id, title, author, category);
}
}
}
Related Resources
This is the last lesson in this section.
Create a free account to earn a certificate