目前我正在为我正在开发的游戏创建一些对话。我想通过 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 项。
请帮帮我!