使用DOM插入和更新XML

时间:2014-03-13 21:01:55

标签: java xml dom

我正在将游戏数据保存在XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<games>
  <player id="1">
    <name>Player 1</name>
    <level>2</level>
    <score>1000</score>
  </player>
  <player id="2">
    <name>Player 2</name>
    <level>4</level>
    <score>7500</score>
  </player>
</games>

如何在xml的末尾插入新的播放器节点,然后更新xml?

1 个答案:

答案 0 :(得分:0)

Element player = document.createElement("player");
player.setAttribute("id","3");

Element name = document.createElement("name");
name.setTextContent("Player 3");
player.appendChild(name);

Element level = document.createElement("level");
level.setTextContent("4");
player.appendChild(level);

Element score = document.createElement("score");
score.setTextContent("10000");
player.appendChild(score);

Element games = document.findElementsByTag("games").item(0);
games.appendChild(player);