В вашем коде 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