我正在编写一个简单的 Java 游戏,我想将玩家数据保存到一个 XML 编码的保存文件中。目前我正在探索 Java XML DOM API,我有一个简短的问题。
假设我有以下 XML 文件(我知道这没有意义,但这只是一个示例)
<?xml version="1.0"?>
<savedGame>
<name></name>
<player>
<name>YOU</name>
<map>
<health>2000</health>
<name>map_test.map</name>
<position>
<x>0</x>
<y>0</y>
</position>
</map>
<stats>
<health>1000</health>
<xp>
<melee></melee>
<magic></magic>
<ranged></ranged>
<agility></agility>
</xp>
</stats>
<items>
<item id="0">
<amount></amount>
</item>
</items>
</player>
</savedGame>
现在我想获取玩家的健康水平(请注意, map 部分中还有其他健康元素)。这可以通过以下代码完成:
String hp = ((Element) ((Element) savedGameDocument.getElementsByTagName("player").item(0)).getElementsByTagName("stats").item(0)).getElementsByTagName("health").item(0).getTextContent()
它有效,是的。但它看起来很讨厌我。这是获取那些嵌套元素的常用方法吗?为什么没有 ElementList 类?现在我必须转换每个节点。
提前致谢, 乔里。
最佳答案
您可以使用 JDK/JRE 中包含的 javax.xml.xpath
API 轻松地从您的 do 文档中获取数据。
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
InputSource xml = new InputSource("src/forum16479976/input.xml");
String health = (String) xpath.evaluate("/savedGame/player/stats/health", xml, XPathConstants.STRING);
System.out.println(health);
}
}
这些 API 也可以从 DOM 访问数据
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xml = db.parse("src/forum16479976/input.xml");
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
String health = (String) xpath.evaluate("/savedGame/player/stats/health", xml, XPathConstants.STRING);
System.out.println(health);
}
}
关于Java XML : get nested element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16479976/