![](/img/trans.png)
[英]How to find Node attribute value and delete it in XML with Java DOM parser
[英]How to parse next node attribute after keypress (Java DOM Parser)
目前,我正在为我正在开发的游戏创建一些对话。 我想通过XML解析来做到这一点。
我在system.out.println中进行了解析,但是它从XML打印所有结果。
XML DOC:
<?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。
请帮帮我!
我的建议是研究Xpath
以及如何在Java中使用它。
在一行中, XPath
是一种节点寻址语言,它使您可以从XML文件中检索适当的节点或一组节点。
由于您具有一个id
属性,该属性对于会话中的每个进度都会增加1,因此您可能希望使用基于id
属性的XPath
检索适当的节点。 只需将id属性记录为一个int
,每按一次该键,此属性就会增加。 然后,基于该值,获取节点。
您的XPath
查询如下所示:
//conversation[@id=2]
这将选择id
属性为2
的conversation
标签。
现在,要获取名称和行,
//conversation[@id=2]/line
和
//conversation[@id=2]/name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.