0

我有一个本地 SQL 表,其中包含以下记录:

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

我想将其转换为如下所示:

<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>

我有一个名为 Tplayers 的类,它获取和设置所有字段,如下所示:

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;
}

最后,我有 DbMethods 类,其中包含一个播放器 Arraylist,我将表中的所有数据存储在“播放器”对象中:

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);
    }
}

现在我想创建一个具有 main 方法的数据库类,该方法在执行时将创建一个类似于所描述的 XML 文件,但我不知道如何开始,我知道如何创建 XML 文档,但只能通过硬编码。非常感谢任何帮助,如果需要任何澄清,请随时询问。

此外,所有导入都在那里我只是没有将它们包含在帖子中以防止混乱发布后我将搜索其他站点以获取更多信息,因此上述代码可能会更改,我会在顶部记录任何更改。

4

2 回答 2

1

既然您基本上已经具备了开始所需的一切,那么我将只关注生成 XML 文档并用数据填充它的基础知识......

这个例子将输出String我显示的结果,但你可以用任何OutputStream你需要的东西来补充它

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();
        }
    }
}

哪个输出...

<?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>

现在,这一切都取自我在过去几年中蹒跚而行的图书馆代码,所以我什至不确定有一个网站可以涵盖所有这些......

于 2013-08-14T02:28:13.533 回答
1

我会使用 JAXB,这是基本思想

@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);
    }
}

输出

<?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>

在此处找到有关 JAXB 的简单教程http://www.vogella.com/articles/JAXB/article.html

于 2013-08-14T03:18:26.107 回答