java - 如何通过元素 id 读取 XML?

标签 java xml xml-parsing

这是我当前的 XML 文件,它为我提供了不同角色的对话,或者至少应该如此。我希望它能够工作,以便我可以指定实体 id 和选项/任务 id 并获取输出。所以我该怎么做?感谢任何帮助,非常感谢。

<?xml version="1.0"?>
<dialoge>
<entity id="1"> <!-- questgiver -->
    <quest id="1">
        <option id="1">
            <precondition>player has not started quest</precondition>
            <output>hello there, can you kill 2 enemies for me?</output>
        </option>
        <option id="2">
            <precondition>player has completed quest and player has not...</precondition>
            <output>thankyou, have a sword for your troubles.</output>
        </option>
        <option id="3">
            <precondition>player has not finished quest</precondition>
            <output>you haven't finished yet.</output>
        </option>
        <option id="4">
            <outpur>thank you.</outpur>
        </option>
    </quest>
</entity>
<entity id="2"> <!-- villager -->
    <option id="1">
        <precondition>village is being destroyed</precondition>
        <output>our village is being destroyed, please help us!</output>
    </option>
    <option id="2">
        <precondition>village has been saved or destroyed</precondition>
        <output>we will never forget this.</output>
    </option>
    <option id="3">
        <output>hello.</output>
    </option>
</entity>
</dialoge>

这是我目前拥有的,但它不起作用。我知道这可能是一个愚蠢的问题,但我在网络上找不到答案。谢谢。

public static void read() {
    try {
        File file = new File("text.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();

        System.out.println("root of xml file " + doc.getDocumentElement().getNodeName());
        NodeList nodes = doc.getElementsByTagName("entity");
        System.out.println("==========================");

        for(int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                        if(element.getElementsByTagName("entity").item(0).getTextContent().equals("output")) {

                }
                System.out.println("" + getValue("output", element));
            }
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
}

private static String getValue(String tag, Element element) {
    NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

最佳答案

最简单的方法可能是使用 XPath...

try {
    File file = new File("text.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression xExpress = xpath.compile("//*[@id='1']");
    NodeList nl = (NodeList) xExpress.evaluate(doc, XPathConstants.NODESET);
    System.out.println("Found " + nl.getLength() + " matches");
} catch (Exception e) {
    e.printStackTrace();
}

xpath 查询 //*[@id='1'] 将查找文档中具有属性 id 且值为 的所有节点1

看看WC3 XPath TutorialHow XPath works有关 XPath 的更多详细信息

关于java - 如何通过元素 id 读取 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900594/

相关文章:

java - 如何使用java下载网页并保存图像文件

Java 内存基准测试

java - 如何从 Java 中的 XML 文件中提取所有 PCDATA(文本)?

java - fatal error :1:40: Content is not allowed in prolog

javascript - 解析多态 XML

xml - Perl:如何解析无效的XML文档?

java - 为什么 Java 的列表迭代器在改变方向时没有返回正确的元素

java - <identifier> 预期,arrayList

java - 使用注释的基本 Spring Web MVC 应用程序

java - 如何使用 Java 中的 StAX 将大 xml 文件分割成小块(小 Xml 文件)