Last Updated:

How to read an XML file in Java: using the DOM Parser

DOM XML Parser is the easiest to understand, as it loads the contents of an XML file into memory as a document that we can easily navigate through.

DOM Parser Great for small XML documents, as it loads a full XML file into memory. For large XML files, you need to use SAX Parser, which we will discuss in future articles.

In this tutorial we will read an XML file and create an object from it.

Let's take a look at the structure of the XML file we'll be working with:

Now let's write the Language class, which will be a single xml block:

<Language>...</Language>

Note that the method that will print useful information about the programming language in a convenient form for us has been overridden.toString()

If you have difficulty understanding the override of methods, I advise you to learn more about the annotation @Override. If you're new and don't know what annotations are, check out the Java Annotation Guide.

The following is a Java program that uses to read and parse an XML file in a list of Language objects:DOM XML Parser

The result of running an XML file reader using the XML Parser DOM: