這是我現在的XML文件,它給了我不同字符的對話,或者至少它應該。我希望它能夠工作,以便我可以指定實體標識和選項/任務標識並獲取輸出。所以我該怎麼做?任何幫助表示讚賞,非常感謝。如何通過元素ID讀取XML?
<?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();
}
如果我想找到只爲'entity'標籤? :) – Braj
'// entity [@ id ='1']'或'// entity'如果你想要所有的實體,不管id值 – MadProgrammer
看到我的xml文件有兩個不同的元素與id的,他們都有孩子也有id的元素,我該如何去尋找它們?我會做實體[@ id ='1'],然後選擇[@ id ='1']嗎?謝謝,這似乎是一個很好的解決方案。 –