чтение XML-файла с помощью Java - PullRequest
0 голосов
/ 28 мая 2018

Я новичок в Java, и я хочу проанализировать XML-файл

У меня есть XML-файл, отформатированный так:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <metadonnees>
        <factory type="factory1">
            <icones>
                <icone type="empty" path="src/ressources/UMP0%.png"/>
                <icone type="half" path="src/ressources/UMP33%.png"/>
                <icone type="full" path="src/ressources/UMP100%.png"/>
            </icones>
            <out type = "materiel1"/>
            <interval>100</interval>
        </factory>
        <factory type="factory2">
            <icones>
                <icone type="empty" path="src/ressources/UT0%.png"/>
                <icone type="half" path="src/ressources/UT33%.png"/>
                <icone type="full" path="src/ressources/UT100%.png"/>
            </icones>
            <enter type="materiel1" quantite="2"/>
            <out type="materiel2"/>
            <interval> 2 </interval>
        </factory>

    </metadonnees>

    <simulation>
        <factory type="factoty1" id="11" x="32" y="32"/>
        <factory type="factory2" id="21" x="320" y="32"/>

        <paths>
            <path de="11" vers="21" />
            <path de="21" vers="41" />
            <path de="41" vers="51" />
            </paths>
    </simulation>

</configuration>

Я пытаюсь прочитать его с помощью Java, но у меня естьнеприятности

NodeList config = document.getElementsByTagName("metadonnees");

for(int j = 0;j<config.getLength();j++) {

    NodeList usineList = document.getElementsByTagName("factory");
    for (int i = 0; i < usineList.getLength(); i++) {
        Node usine = usineList.item(i);
        if (usine.getNodeType() == Node.ELEMENT_NODE) {
            Element type = (Element) usine;
            String typeUsine = type.getAttribute("type");

            System.out.println(typeUsine);
        }
    }
}

этот список мне только фабричный тип

  • фабрика1
  • фабрика2
  • фабрика1
  • фабрика2

Я хочу перечислить только данные в метадонном разделе, чтобы я мог получить заводские настройки и как получить айконы отдельно

Как мне решить эту проблему?

Ответы [ 2 ]

0 голосов
/ 23 июня 2018

SimpleXml может сделать это:

final String data = ...
final SimpleXml simple = new SimpleXml();
final Element element = simple.fromXml(data);
for (final Element factory : element.children.get(0).children) {
    for (final Element icone : factory.children.get(0).children) {
        System.out.println(String.format("Factory: %s, Icone: %s", factory.attributes.get("type"), icone.attributes.get("type")));
    }
}

Будет выводить:

Factory: factory1, Icone: empty
Factory: factory1, Icone: half
Factory: factory1, Icone: full
Factory: factory2, Icone: empty
Factory: factory2, Icone: half
Factory: factory2, Icone: full

Из maven central:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.4.0</version>
</dependency>
0 голосов
/ 29 мая 2018

В вашем коде document.getElementsByTagName("factory"); возвращает все элементы, имеющие тег <factory>.Если вы хотите ограничить выбор в метаданных раздела metadonnees, вы можете использовать XPath (XML Path Language).

Получить элементы

Получает все элементы factory в метаданных:

//metadonnees/factory

Java-код:

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//metadonnees/factory");
NodeList usineList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < usineList.getLength(); i++) {
  Element usine = (Element) usineList.item(i);
  String typeUsine = usine.getAttribute("type");
  System.out.println(typeUsine);
}

Получить атрибуты

Получает все type атрибуты factory элементов в метаданных:

//metadonnees/factory/@type

Java-код:

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//metadonnees/factory/@type");
NodeList typeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < typeList.getLength(); i++) {
  Attr type = (Attr) typeList.item(i);
  System.out.println(type.getValue());
}

Получение подузлов

При запросе к подузлам фабрики вам нужен следующий xpath, что означает, что запрос начинается с текущего узла (.)и продолжается до достижения элемента <icone>:

.//icone

Java-код:

XPath xPath = XPathFactory.newInstance().newXPath();
NodeList usineList =
    (NodeList) xPath.evaluate("//metadonnees/factory", document, XPathConstants.NODESET);
for (int i = 0; i < usineList.getLength(); i++) {
  Element usine = (Element) usineList.item(i);
  NodeList icons = (NodeList) xPath.evaluate(".//icone", usine, XPathConstants.NODESET);
  System.out.println(usine.getAttribute("type"));

  for (int j = 0; j < icons.getLength(); j++) {
    Element icon = (Element) icons.item(j);
    String type = icon.getAttribute("type");
    String path = icon.getAttribute("path");
    String msg = "type=" + type + ", path=" + path;
    System.out.println(msg);
  }
}

Результат:

factory1
type=empty, path=src/ressources/UMP0%.png
type=half, path=src/ressources/UMP33%.png
type=full, path=src/ressources/UMP100%.png
factory2
type=empty, path=src/ressources/UT0%.png
type=half, path=src/ressources/UT33%.png
type=full, path=src/ressources/UT100%.png
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...