Это мой текущий файл XML, он дает мне диалог для разных персонажей или, по крайней мере, должен. Я хочу, чтобы он работал, чтобы я мог указать идентификатор объекта и идентификатор опции/квеста и получить результат. И что же мне делать? Любая помощь приветствуется, большое вам спасибо.Как читать 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-файл имеет два разных элемента с идентификатором, и оба они имеют дочерние элементы, которые также имеют идентификаторы, как мне их найти? Я бы сделал entity [@ id = '1'], а затем option [@ id = '1']? Спасибо, и это кажется хорошим решением. –