Skip to content

Parsing A Basic XML File

Jmesmer edited this page Mar 7, 2022 · 15 revisions

The basic XML file program creates a Credentials (super class) and Password class. The Credentials class stores information pertaining to the credentials information located in the XML file. The Credentials class stores the host, port, user and password information. The Password class produces a hint attribute that hints at the password inside of the credentials object. The Main class creates a Serializer object, a File object and a Credentials object.

The XML File To Parse

The XML file known as woz.xml goes as follows:

<?xml version="1.0"?>
<credentials>
 <host>woz.cs.missouriwestern.edu</host>
 <port>33006</port> <!--This isn't the right port, by the way -->
 <user>csc</user>
 <password xhint="room where woz is located It definitily is not '!😈湯🦊🚴'">********</password>
</credentials>

The goal of the simple use case is to parse out the host, the port, the user, and the passwords hint.

The Main Line

   public static void main(String[] args) throws Exception {
        //We create a serializer and a Persister in order to grab the elements from the XML file.
        Serializer serializer = new Persister();
        //We grab from the source "woz.xml"
        File source = new File("woz.xml");
        //We then create a Credentials object and use the serializer to read from the source file and convert to
        // the Credentials.class objects.
        Credentials credentials = serializer.read(Credentials.class, source);
        System.out.println(credentials.toString());
    }//End of main
}//End of SimpleUseCase.class

The Credentials Class

@Root
class Credentials{
//We grab the host element
    @Element
    private String host;

    //We grab the port element
    @Element
    private int port;

    //We grab the user element
    @Element
    private String user;

    //We grab the password element, which will be a Password object.
    @Element
    private Password password;

    //The constructor is used to create the object from the various elements from the XML file
    public Credentials(){
        super();
    }//end of constructor

    //Returns the host variable
    public String getHost() {
        return host;
    }//End of getHost

    //Returns the port variable
    public int getPort() {
        return port;
    }//End of getPort

    //Returns the user variable
    public String getUser() {
        return user;
    }//End of getUser

    //Returns the password hint
    public String getPassword(){
        return password.getXhint();
    }//End of getPassword

}

The Password Class:

@Root
class Password{

    //We grab the attrube known as xhint from the password element;
    @Attribute
    private String xhint;

    //Returns the xhint variable
    public String getXhint(){
        return xhint;
    }//End of getXhint
}//End of Password.class

Clone this wiki locally