【发布时间】:2013-11-16 12:33:45
【问题描述】:
目前我正在为我正在开发的游戏创建一些对话。 我想通过 XML 解析来做到这一点。
我在 system.out.println 中进行了解析,但它会打印 XML 中的所有结果。
XML 文档:
<?xml version="1.0"?>
<cutscene>
<conversation id="1">
<name>Rubeus Hagrid</name>
<line>Sorry about the door..</line>
</conversation>
<conversation id="2">
<name>Herman Duffeling</name>
<line>I want you to leave immediately, this is my home!</line>
</conversation>
<conversation id="3">
<name>Rubeus Hagrid</name>
<line>Oh, shut up..</line>
</conversation>
</cutscene>
Java 源代码:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("Resources/XML/conversations.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("conversation");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println(eElement.getAttribute("id"));
System.out.println(eElement.getElementsByTagName("name").item(0).getTextContent() + ": ");
System.out.println(eElement.getElementsByTagName("line").item(0).getTextContent());
System.out.println("---------------------------");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
代码打印如下:
1
Rubeus Hagrid:
Sorry about the door..
---------------------------
2
Herman Duffeling:
I want you to leave immediately, this is my home!
---------------------------
3
Rubeus Hagrid:
Oh, shut up..
---------------------------
这就是我想做的:
1
Rubeus Hagrid:
Sorry about the door..
---------------------------
当您在此处单击一个键时(我在考虑 Enter 键),您需要查看下一个项目,因此它是数字 2。
请帮帮我!
【问题讨论】:
标签: java xml parsing dom keypress