Проблема с анализом XML-файла в первый раз - PullRequest
0 голосов
/ 22 сентября 2019

Я впервые разбираю XML-файл для домашней работы, которая у меня есть.У меня проблема, которая, вероятно, является чем-то глупым, но я не могу найти, что идет не так.Некоторые фрагменты написаны на французском языке, так как это мой основной язык.

Вот фрагмент кода, с которым у меня проблемы.Итак, с этими последними строками кода я могу напечатать информацию, которую мне нужно отправить моему конструктору.

public void ParseXML(File fichierXML){

        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        {
            try {
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(fichierXML);
                final Element racine = document.getDocumentElement();
                final NodeList racineNoeuds = racine.getChildNodes();
                final int nbRacineNoeuds = racineNoeuds.getLength();

                // Adjusting XML file
                document.getDocumentElement().normalize();

                // Printing out the main node
                System.out.println("Racine (root) : " + racine.getNodeName());

                for (int i = 0; i<nbRacineNoeuds; i++)
                {
                    if(racineNoeuds.item(i).getNodeType() == Node.ELEMENT_NODE)
                    {
                        final Element sousSection = (Element) racineNoeuds.item(i);
                        System.out.println("Sous-section : " + sousSection.getNodeName());

                        final NodeList usines = sousSection.getElementsByTagName("usine");
                        final int nbUsinesElements = usines.getLength();

                        for(int j = 0; j<nbUsinesElements; j++) {

                            final Element usine = (Element) usines.item(j);
                            String type = usine.getAttribute("type");
                            System.out.println(usine.getAttribute("type"));
                            String StringId = usine.getAttribute("id");
                            System.out.println(usine.getAttribute("id"));
                            String StringX = usine.getAttribute("x");
                            System.out.println(usine.getAttribute("x"));
                            String StringY = usine.getAttribute("y");
                            System.out.println(usine.getAttribute("y"));

                            //int id = Integer.parseInt(StringId);
                            //int x = Integer.parseInt(StringX);
                            //int y = Integer.parseInt(StringY);

                            //AjouterBatiment(new Usine(1, ImageIO.read(new File(("src/ressources/UMP0%.png"))),
                            //        new Point(x,y), 100));
                        }
                    }
                }

            } catch (ParserConfigurationException | IOException | SAXException |  NumberFormatException e) {
                e.printStackTrace();
            }

        }

    }

Теперь, когда я удаляю комментарии из строк, где я пытаюсь назначить ихСтроковая переменная, если я проверяю отладчик, я вижу, что они пусты.Я не понимаю, почему, потому что они просто распечатали одну строку раньше.

Так что, очевидно, у меня возникает ошибка после этого, когда я пытаюсь преобразовать строку, я получаю в int, потому что переменная пуста.

Вот 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>
        <usine type="usine-moteur">
            <icones>           
                <icone type="vide" path="src/ressources/UM0%.png"/>
                <icone type="un-tiers" path="src/ressources/UM33%.png"/>
                <icone type="deux-tiers" path="src/ressources/UM66%.png"/>
                <icone type="plein" path="src/ressources/UM100%.png"/>
            </icones>
            <entree type="metal" quantite="4"/>
            <sortie type="moteur"/>
            <interval-production>75</interval-production>
        </usine>
        <usine type="usine-assemblage">
            <icones>
                <icone type="vide" path="src/ressources/UA0%.png"/>
                <icone type="un-tiers" path="src/ressources/UA33%.png"/>
                <icone type="deux-tiers" path="src/ressources/UA66%.png"/>
                <icone type="plein" path="src/ressources/UA100%.png"/>
            </icones>
            <entree type="aile" quantite="2"/>
            <entree type="moteur" quantite="4"/>
            <sortie type="avion"/>
            <interval-production>110</interval-production>
        </usine>
        <usine type="entrepot">
            <icones>
                <icone type="vide" path="src/ressources/E0%.png"/>
                <icone type="un-tiers" path="src/ressources/E33%.png"/>
                <icone type="deux-tiers" path="src/ressources/E66%.png"/>
                <icone type="plein" path="src/ressources/E100%.png"/>
            </icones>
            <entree type="avion" capacite="5"/>
        </usine>
    </metadonnees>

    <simulation>
        <usine type="usine-matiere" id="11" x="32" y="32"/>
        <usine type="usine-aile" id="21" x="320" y="32"/>
        <usine type="usine-assemblage" id="41" x="160" y="192"/>
        <usine type="entrepot" id="51" x="640" y="192"/>
        <usine type="usine-matiere" id="13" x="544" y="576"/>
        <usine type="usine-matiere" id="12" x="96" y="352"/>
        <usine type="usine-moteur" id="31" x="320" y="352"/>
        <chemins>
            <chemin de="11" vers="21" />
            <chemin de="21" vers="41" />
            <chemin de="41" vers="51" />
            <chemin de="12" vers="31" />
            <chemin de="13" vers="31" />
            <chemin de="31" vers="41" />
        </chemins>
    </simulation>

</configuration>

Вот вывод распечаток:

usine-assemblage
41
160
192
entrepot
51
640
192
usine-matiere
13
544
576
usine-matiere
12
96
352
usine-moteur
31
320
352

Любая помощь будет очень признательна, так как я работаю над этой конкретной проблемойс прошлой ночи без особой удачи.

Спасибо!

1 Ответ

0 голосов
/ 22 сентября 2019

Ваш элемент "usine" появляется в двух разделах - метаданные и симуляция.Полный вывод выглядит следующим образом:

Racine : configuration
Sous-section : metadonnees
usine-matiere



usine-aile



usine-moteur



usine-assemblage



entrepot



Sous-section : simulation
usine-matiere
11
32
32
usine-aile
21
320
32
usine-assemblage
41
160
192
entrepot
51
640
192
usine-matiere
13
544
576
usine-matiere
12
96
352
usine-moteur
31
320
352

Когда отладчик останавливает ваш код в точке останова, он останавливается каждый раз, когда заданная строка «удаляется».Первые 5 попаданий включают элементы из «metadonnes», как показано в выходных данных - поэтому здесь нет проблем, так как элементы из «metadonnes» не содержат атрибутов x, y и id.Вам нужно пропустить первые 5 остановок, чтобы получить нужные данные в отладчике.

Что нужно сделать, чтобы игнорировать эти «пустые» записи - просто игнорировать все из узла «metadonnes».Один из подходов состоит в том, чтобы входить в цикл, который извлекает атрибуты x, y и id, только когда выполняется синтаксический анализ раздела «симуляция».

for(int j = 0; "simulation".equals(sousSection.getNodeName()) && j<nbUsinesElements; j++) {

Эта модификация позволит вам пропустить все, что не находится в "симуляция "узел

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...