Java XML Tutorial

Java – Convert XML to a properties file

This article shows how to convert an XML file to a properties file.

Table of contents

P.S Tested with Java 11.

1. Properties – Convert XML file to a properties file

The below example uses Properties#loadFromXML() to loads an XML file and converts it to properties values.

1.1 An XML file using the properties.dtd.

server.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>Server config file</comment>
    <entry key="http.port">8080</entry>
    <entry key="email.support">[email protected]</entry>
    <entry key="http.server">localhost</entry>
    <entry key="http.port">8080</entry>
</properties>

1.2 We can use Properties#loadFromXML() to loads an XML file into the properties values.

ConvertXmlToProperties.java

package com.mkyong.xml.tips;

import java.io.*;
import java.util.Properties;

public class ConvertXmlToProperties {

    public static void main(String[] args) throws IOException {

        Properties props = new Properties();
        try (InputStream input =
                     new FileInputStream("src/main/resources/server.xml")) {
            // loads from XML into a properties file
            props.loadFromXML(input);
        }

        try (OutputStream output =
                     new FileOutputStream("c:\\test\\server.properties")) {

            props.store(output, "");

        }

    }

}

1.3 Output – c:\\test\\server.properties


#
#Sun May 16 16:51:31 SGT 2021
http.port=8080
[email protected]
http.server=localhost

1.4 For Properties#loadFromXML() to work properly, the XML document must have the following DOCTYPE declaration:


  <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

Since we declare the DOCTYPE and properties.dtd, the XML document must also follow the following properties.dtd format.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="key1">value1</entry>
</properties>

If the XML file failed to follow the above format defined in properties.dtd, JDK would throw an error message from loading the XML file.

2. DOM – Convert XML file to a properties file

This example uses a DOM parser to read the XML file and convert the value into a properties file.

2.1 An XML file.

staff.xml

<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff id="1001">
        <name>mkyong</name>
    </staff>
    <staff id="1002">
        <name>yflow</name>
    </staff>
</company>

2.2 DOM parser to read XML and convert it to Properties object.

ConvertXmlToPropertiesDom.java

package com.mkyong.xml.tips;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.Properties;

public class ConvertXmlToPropertiesDom {

    public static void main(String[] args)
            throws IOException, ParserConfigurationException, SAXException {

        Document doc;
        Properties prop = new Properties();

        try (FileInputStream input =
                     new FileInputStream("src/main/resources/staff.xml")) {
            // convert XML file to Document
            doc = parse(input);
        }

        NodeList list = doc.getElementsByTagName("staff");

        for (int temp = 0; temp < list.getLength(); temp++) {

            Node node = list.item(temp);

            if (node.getNodeType() == Node.ELEMENT_NODE) {

                Element element = (Element) node;

                // get staff's id
                String id = element.getAttribute("id");

                // get text
                String name = element.getElementsByTagName("name")
                        .item(0).getTextContent();

                // write value to properties
                // prop does not guarantee on the order
                prop.setProperty("company.staff" + temp + ".id", id);
                prop.setProperty("company.staff" + temp + ".name", name);

            }

        }

        // write to console for testing
        prop.store(System.out, "");

        // write to a properties file
        /*try (FileOutputStream output =
                     new FileOutputStream("c:\\test\\staff.properties")) {
            prop.store(output, "");
        }*/

    }

    // get document
    private static Document parse(InputStream input)
            throws ParserConfigurationException, IOException, SAXException {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(input);
        return doc;

    }

}

Output

Terminal

#
#Sun May 16 17:43:20 SGT 2021
company.staff0.name=mkyong
company.staff0.id=1001
company.staff1.name=yflow
company.staff1.id=1002

How about SAX, StAX, JDOM, and JAXB?
The above DOM parser idea works for all the other XML parsers such as SAX, StAX, JDOM, or JAXB. We use an XML parser to read the XML values and store them in a Properties object.

3. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-xml

$ cd src/main/java/com/mkyong/xml/tips/

4. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Kendly Paul
6 years ago

thank you!