Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6549851
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T12:08:39+00:00 2026-05-25T12:08:39+00:00

I have to read and write to and from an XML file. What is

  • 0

I have to read and write to and from an XML file. What is the easiest way to read and write XML files using Java?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T12:08:39+00:00Added an answer on May 25, 2026 at 12:08 pm

    Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE roles SYSTEM "roles.dtd">
    <roles>
        <role1>User</role1>
        <role2>Author</role2>
        <role3>Admin</role3>
        <role4/>
    </roles>
    

    and the dtd:

    <?xml version="1.0" encoding="UTF-8"?>
    <!ELEMENT roles (role1,role2,role3,role4)>
    <!ELEMENT role1 (#PCDATA)>
    <!ELEMENT role2 (#PCDATA)>
    <!ELEMENT role3 (#PCDATA)>
    <!ELEMENT role4 (#PCDATA)>
    

    First import these:

    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import org.xml.sax.*;
    import org.w3c.dom.*;
    

    Here are a few variables you will need:

    private String role1 = null;
    private String role2 = null;
    private String role3 = null;
    private String role4 = null;
    private ArrayList<String> rolev;
    

    Here is a reader (String xml is the name of your xml file):

    public boolean readXML(String xml) {
            rolev = new ArrayList<String>();
            Document dom;
            // Make an  instance of the DocumentBuilderFactory
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
                // use the factory to take an instance of the document builder
                DocumentBuilder db = dbf.newDocumentBuilder();
                // parse using the builder to get the DOM mapping of the    
                // XML file
                dom = db.parse(xml);
    
                Element doc = dom.getDocumentElement();
    
                role1 = getTextValue(role1, doc, "role1");
                if (role1 != null) {
                    if (!role1.isEmpty())
                        rolev.add(role1);
                }
                role2 = getTextValue(role2, doc, "role2");
                if (role2 != null) {
                    if (!role2.isEmpty())
                        rolev.add(role2);
                }
                role3 = getTextValue(role3, doc, "role3");
                if (role3 != null) {
                    if (!role3.isEmpty())
                        rolev.add(role3);
                }
                role4 = getTextValue(role4, doc, "role4");
                if ( role4 != null) {
                    if (!role4.isEmpty())
                        rolev.add(role4);
                }
                return true;
    
            } catch (ParserConfigurationException pce) {
                System.out.println(pce.getMessage());
            } catch (SAXException se) {
                System.out.println(se.getMessage());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
            }
    
            return false;
        }
    

    And here a writer:

    public void saveToXML(String xml) {
        Document dom;
        Element e = null;
    
        // instance of a DocumentBuilderFactory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // use factory to get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();
            // create instance of DOM
            dom = db.newDocument();
    
            // create the root element
            Element rootEle = dom.createElement("roles");
    
            // create data elements and place them under root
            e = dom.createElement("role1");
            e.appendChild(dom.createTextNode(role1));
            rootEle.appendChild(e);
    
            e = dom.createElement("role2");
            e.appendChild(dom.createTextNode(role2));
            rootEle.appendChild(e);
    
            e = dom.createElement("role3");
            e.appendChild(dom.createTextNode(role3));
            rootEle.appendChild(e);
    
            e = dom.createElement("role4");
            e.appendChild(dom.createTextNode(role4));
            rootEle.appendChild(e);
    
            dom.appendChild(rootEle);
    
            try {
                Transformer tr = TransformerFactory.newInstance().newTransformer();
                tr.setOutputProperty(OutputKeys.INDENT, "yes");
                tr.setOutputProperty(OutputKeys.METHOD, "xml");
                tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
                tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
                // send DOM to file
                tr.transform(new DOMSource(dom), 
                                     new StreamResult(new FileOutputStream(xml)));
    
            } catch (TransformerException te) {
                System.out.println(te.getMessage());
            } catch (IOException ioe) {
                System.out.println(ioe.getMessage());
            }
        } catch (ParserConfigurationException pce) {
            System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
        }
    }
    

    getTextValue is here:

    private String getTextValue(String def, Element doc, String tag) {
        String value = def;
        NodeList nl;
        nl = doc.getElementsByTagName(tag);
        if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
            value = nl.item(0).getFirstChild().getNodeValue();
        }
        return value;
    }
    

    Add a few accessors and mutators and you are done!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to read and write from serial using events/interrupts. Currently, I have it
I have to write a program that read from a file that contains the
I have a text read from a XML file stored in UTF8 encoding. C#
OK, I managed to read from an XML file using NSXMLParser , but now
I have to read/write an XML file that stores its data as bit masked
I have two (UNIX) programs A and B that read and write from stdin/stdout.
I have a problem to write and read properly a CSV file composed of
I have an XMLDocument that I have read in from file. The file is
I'm trying to read xml file from vbs script. Xml is encoded in utf-8
I have code in C++ for saving and retrieving data from an XML file.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.