Calsolum
Calsolum

Reputation: 109

Generate an xml file using DOM

I have a local SQL table has these records in it:

ID    currentRank     previousRank      PlayerName  Money
1           1                1            Max        15
2           2                2            Rick       20
3           3                3            Alice      13
4           4                4            Beth       25

I want to convert it to make it look like this:

<player ID="1">
    <currentRank>1</currentRank>
    <previousRank>1</previousRank>
    <PlayerName>Max</PlayerName>
    <Money>15</Money>
</player>

<player ID="2">
    <currentRank>2</currentRank>
    <previousRank>2</previousRank>
    <PlayerName>Rick</PlayerName>
    <Money>20</Money>
</player>

<player ID="3">
    <currentRank>3</currentRank>
    <previousRank>3</previousRank>
    <PlayerName>Alice</PlayerName>
    <Money>13</Money>
</player>

<player ID="4">
    <currentRank>4</currentRank>
    <previousRank>4</previousRank>
    <PlayerName>Alice</PlayerName>
    <Money>13</Money>
</player>

I have a class called Tplayers that gets and sets all the fields that looks like:

public class Tplayers implements Serializable
{
  private int ID;
  private String currentRank
  private String previousRank
  private String PlayerName
  private String Money
}

public Tplayers () {
ID = 0;
currentRank = "";
previousRank = "";
PlayerName = "";
Money = "";
}


public Tplayers (int playerId, String currentRank, String previousRank, String PlayerName, String Money) {
    this.playerId = playerId;
    this.currentRank = currentRank;
    this.previousRank = previousRank;
    this.PlayerName = PlayerName;
    his.Money = Money;
}

public int getID() {
    return ID;
}

public void setID(int ID) {
    this.ID = ID;
}

public String getCurrentRank() {
   return currentRank;
}

public void setCurrentRank(String currentRank) {
    this.currentRank = currentRank;
}

public String getPreviousRank() {
    return previousRank;
}

public void setPreviousRank(String previousRank) {
    this.previousRank = previousRank;
}

public String getPlayerName() {
    return PlayerName;
}

public void setPlayerName(String PlayerName) {
    this.PlayerName = PlayerName;
}

public String getMoney() {
    return Money;
}

public void setMoney(String Money) {
    this.Money = Money;
}

Finally I have DbMethods Class which contains a players Arraylist where I have stored all of the data from the tables in 'player' objects:

public static ArrayList<Tplayers > getAllPlayers() {

    ArrayList<Tplayers > players = new ArrayList();

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        conn = DBConnectionFactory.getConnection();

        String sql = "SELECT * FROM players";

        ps = conn.prepareStatement(sql);

        rs = ps.executeQuery();

        while (rs.next()) {
            Tplayers player = new Tplayers();
            player.setID(rs.getInt("ID"));
            player.setCurrentRank(rs.getString("CurrentRank"));
            player.setPreviousRank(rs.getString("PreviousRank"));
            player.setPlayerName(rs.getString("PlayerName"));
            player.setMoney(rs.getString("Money"));

            players.add(player);
        }

        return players;

    } catch (SQLException e) {
        System.err.println("Message: " + e.getMessage());
        System.err.println("SQL State: " + e.getSQLState());
        System.err.println("Error Code: " + e.getErrorCode());
        return null;
    } finally {
        DBConnectionFactory.close(rs);
        DBConnectionFactory.close(ps);
        DBConnectionFactory.close(conn);
    }
}

Now I want to create a database class with a main method that upon execution will create an XML file that resembles the one described but I'm not sure how to start, I know how to create an XML document but only by hard coding it. Any assistance is greatly appreciated and if any clarification is needed do not hesitate to ask.

Also all imports are there I just didn't include them in the post to prevent clutter After posting this I will be searching other sites for more information so the above code may change and I will note any changes at the top.

Upvotes: 0

Views: 83

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

Seen as you basically have every thing you need to get started, I'm only going to focus on the basics of generating a XML document and populating it with data...

This example will output the result to String which I display, but you can supplement it with any OutputStream you need

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLTest {

    public static void main(String[] args) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            // Create a new document
            Document xmlDoc = builder.newDocument();
            // Create root node for the document...
            Element root = xmlDoc.createElement("Players");
            xmlDoc.appendChild(root);

            //----> Add a for-loop here <---
            // Then with each player reference, fill out the deatils
            // similar to below....

            // Create a "player" node
            Element player = xmlDoc.createElement("player");
            // Set the players ID attribute
            player.setAttribute("ID", "1");

            // Create currentRank node...
            Element currentRank = xmlDoc.createElement("currentRank");
            currentRank.setTextContent("1");
            player.appendChild(currentRank);

            // Create previousRank node...
            Element previousRank = xmlDoc.createElement("previousRank");
            previousRank.setTextContent("1");
            player.appendChild(previousRank);

            // Create playerName node...
            Element playerName = xmlDoc.createElement("PlayerName");
            playerName.setTextContent("Max");
            player.appendChild(playerName);

            // Create Money node...
            Element money = xmlDoc.createElement("Money");
            money.setTextContent("15");
            player.appendChild(money);

            // Add the player to the root node...
            root.appendChild(player);

            // ---> End for-loop <--- //

            ByteArrayOutputStream baos = null;

            try {
                baos = new ByteArrayOutputStream();

                Transformer tf = TransformerFactory.newInstance().newTransformer();
                tf.setOutputProperty(OutputKeys.INDENT, "yes");
                tf.setOutputProperty(OutputKeys.METHOD, "xml");
                tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                DOMSource domSource = new DOMSource(xmlDoc);
                StreamResult sr = new StreamResult(baos);
                tf.transform(domSource, sr);

                baos.flush();
                System.out.println(new String(baos.toByteArray()));
            } finally {
                try {
                    baos.close();
                } catch (Exception e) {
                }
            }

        } catch (IOException | TransformerException exp) {
            exp.printStackTrace();
        } catch (ParserConfigurationException exp) {
            exp.printStackTrace();
        }
    }
}

Which outputs...

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Players>
    <player ID="1">
        <currentRank>1</currentRank>
        <previousRank>1</previousRank>
        <PlayerName>Max</PlayerName>
        <Money>15</Money>
    </player>
</Players>

Now, this is all taken from library code I've hobbled together of the past few years, so I'm not even sure of a single website which would cover all this...

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136052

I would use JAXB, here is the basic idea

@XmlRootElement(name="players")
public class Test1 {
    @XmlElement(name="player")
    List<Tplayers> list = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        Test1 t1 = new Test1();
        ... add players to list
        JAXB.marshal(t1, System.out);
    }
}

output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<players>
    <player>
        <currentRank></currentRank>
        <ID>0</ID>
        <money></money>
        <playerName></playerName>
        <previousRank></previousRank>
    </player>
    <player>
        <currentRank></currentRank>
        <ID>0</ID>
        <money></money>
        <playerName></playerName>
        <previousRank></previousRank>
    </player>
</players>

find a simple tutorial on JAXB here http://www.vogella.com/articles/JAXB/article.html

Upvotes: 1

Related Questions