DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. 3 Steps to Writing and Reading XML Files

3 Steps to Writing and Reading XML Files

If you're dealing with XML files, you're probably looking to marshal and unmarshal them. JAXB can lend a hand, making reading and writing XML files a three-step process.

Amuda Adeolu user avatar by
Amuda Adeolu
·
Apr. 23, 17 · Tutorial
Like (8)
Save
Tweet
Share
49.89K Views

Join the DZone community and get the full member experience.

Join For Free

To read or write XML files, you should consider JAXB (Java Architecture for XML Binding). JAXB will convert and reconvert XML objects using marshalling (writing to XML) and unmarshalling processes.

When and Where Do I Need to Write XML Files?

Creating a Custom Configuration or UI File

Suppose, in a project, you need to customize the User Data for each field or configure the system’s database to your standard.

Building a Generic XML File for Documentation and Installation

Alternatively, suppose you want to a make a configuration file for all users in order to access and process their data fields.

Your Task

Develop an XML configuration for all web users using their name, IP address, and location as their identifier.

Solution

Step one: Create the specified POJO with an annotation for the task:

package com.mytask.taska.personal;
import javax.xml.bind.annotation.*; // will be using XmlAttribute, XmlElement , XmlRootElement classes from this package
import java.util.*;// will be using Map and List classes from this package
@XmlRootElement
public class User
{
     Map<String,Long> uNameAndHashCode = new TreeMap<>();
     List userIpAddress = new LinkedList<>();

    public List getUserIpAddress()
    {
        return userIpAddress;
    }
    @XmlElement
    public void setUserIpAddress(List newIpAddress)
    {
        this.userIpAddress = newIpAddress;
    }
    public Map<String,Long> getuNameAndHashCode()
    {
        return uNameAndHashCode;
    }
    @XmlElement
    public void setuNameAndHashCode ( Map<String,Long> newUNameAndHcode) {
        this.uNameAndHashCode = newUNameAndHcode;
    }

}


Note: We use the JAXB annotation for jaxbMarshaller.marshal jaxbMarshaller.unmarshal().

Now we write the created User POJO content to an XML file:

package com.mytask.taska.personal;
import java.io.*; // will be using only File class from this package
import javax.xml.bind.*; // will be using JAXBContext,Marshaller and JAXBException classes from this package
public class UserXML {
    public static void main(String[] args) {
        User user = new User();
        user.uNameAndHashCode.put("Amuda Adeolu Badmus", (long) 892382323.23323233);
        user.uNameAndHashCode.put("Vipin Jaiswal", (long) 323783292.32323);
        user.setuNameAndHashCode(user.uNameAndHashCode);

        user.userIpAddress.add("10.199.212.2");
        user.userIpAddress.add("10.232.012.0");
        user.setUserIpAddress(user.userIpAddress);
        try {
            File file = new File("C:\\Users\\User\\Music\\userConfigData.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(user, file);
            jaxbMarshaller.marshal(user, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


....

JAXB ( Marshalling , Un Mashalling )

And lastly, step three: Read the created UserXML File for the task:

package com.mytask.taska.personal;
import java.io.*; // will be using only File class from this package
import javax.xml.bind.*; // will be using JAXBContext,UnMarshaller and JAXBException classes from this package
public class ReadUserXML {
    public static void main(String[] args) {
        try {
            File file = new File("C:\\Users\\User\\Music\\userConfigData.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            User myUser = (User) jaxbUnmarshaller.unmarshal(file);
            System.out.println(myUser);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}
XML

Published at DZone with permission of Amuda Adeolu. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Check Docker Images for Vulnerabilities
  • Express Hibernate Queries as Type-Safe Java Streams
  • Mr. Over, the Engineer [Comic]
  • How Observability Is Redefining Developer Roles

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: