如何在按键后解析下一个节点属性(Java DOM Parser)

时间:2013-11-05 15:16:58

标签: java xml parsing dom keypress

目前我正在为我正在进行的游戏创建一些对话。 我想通过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..
 ---------------------------

当你点击这里的一个键时(我正在考虑输入键),你需要看到下一个项目,这样就是数字2。

请帮帮我!

1 个答案:

答案 0 :(得分:0)

我的建议是研究Xpath以及如何在Java中使用它 在一行中,XPath是一种节点寻址语言,允许您从XML文件中检索适当的节点或一组节点。

由于您的会话中的每个进度都有id属性增加1,因此您可能希望根据XPath属性使用id检索正确的节点。只需将id属性跟踪为int即可在每次按键时增加。然后,根据值,获取节点。

您的XPath查询如下:

//conversation[@id=2]  

这会选择conversation属性为id的{​​{1}}标记 现在,要获取名称和行,

2

//conversation[@id=2]/line