первый пост здесь. У меня есть файл XML, который содержит тег «usine» несколько раз, и я делаю это неправильно, и я хочу посмотреть, есть ли более оптимальный способ сделать это. Я впервые работаю с XML и Node / NodeList, поэтому я все еще знакомлюсь с ним.
Вот файл XML
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<metadonnees>
<usine type="usine-matiere">
<icones>
<icone type="vide" path="src/ressources/UMP0%.png"/>
<icone type="un-tiers" path="src/ressources/UMP33%.png"/>
<icone type="deux-tiers" path="src/ressources/UMP66%.png"/>
<icone type="plein" path="src/ressources/UMP100%.png"/>
</icones>
<sortie type = "metal"/>
<interval-production>100</interval-production>
</usine>
<usine type="usine-aile">
<icones>
<icone type="vide" path="src/ressources/UT0%.png"/>
<icone type="un-tiers" path="src/ressources/UT33%.png"/>
<icone type="deux-tiers" path="src/ressources/UT66%.png"/>
<icone type="plein" path="src/ressources/UT100%.png"/>
</icones>
<entree type="metal" quantite="2"/>
<sortie type="aile"/>
<interval-production>50</interval-production>
</usine>
</metadonnees>
<simulation>
<usine type="usine-matiere" id="11" x="32" y="32"/>
<usine type="usine-aile" id="21" x="320" y="32"/>
<chemins>
<chemin de="11" vers="21" />
<chemin de="21" vers="41" />
</chemins>
</simulation>
Например, если я хочу получить значение x 'usine type = "usine-aile"' в теге имитации, вот код, который я использую:
NodeList nList = doc.getElementsByTagName("simulation");
Node positionNode = nList.item(0);
Element elementPosition = (Element) positionNode;
NodeList cooList = elementPosition.getElementsByTagName("usine");
Node cooNode = cooList.item(0);
Element cooElem = (Element) cooNode;
System.out.println(cooElem.getAttribute("x"));
В основном я должен сделать два NodeList, потому что нужный мне элемент находится в теге, а не тот, что в теге, поэтому первый NodeList должен найти меня в теге, а затем я go глубже создаю новый NodeList, чтобы найти нужный мне. Есть лучший способ сделать это? Я, вероятно, делаю это неправильно, поэтому я буду знать ваши ответы. Спасибо