0

So I am trying to iterate through an XML file to retrieve certain values for further usage.

    public static void readFile() throws ParserConfigurationException, IOException, SAXException {

    File file = new File("TrafficLightPatterns.xml");
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(file);


    NodeList nodeList = document.getElementsByTagName("lights");

    IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item).filter(node ->
            node.getNodeType() == Node.ELEMENT_NODE).map(Node::getTextContent).map(value -> "value:" + value)
            .forEach(System.out::println);

    System.out.println(nodeList);
}

I managed to retrieve every value that is inside <lights> tags, but now I am trying to retrieve only those that are part of a specific row, preferably by their ID. How can I manage this?

XML looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
<root>
  <row id="Germany">
    <lights>
      <light>redLight,circle</light>
      <light>yellowLight,circle</light>
      <light>greenLight,circle</light>
    </lights>
    <behaviour>
      <stop>1,2</stop>
      <stop>1</stop>
      <go>1,2</go>
      <go>3</go>
      <night>2</night>
      <night>0</night>
    </behaviour>
  </row>

  <row id="GermanyWesel">
    <lights>
      <light>redLight,donkey</light>
      <light>yellowLight,donkey</light>
      <light>greenLight,donkey</light>
    </lights>
    <behaviour refid="Germany"/>
  </row>

  <row id="Netherlands">
    <lights>
      <light>redLight,circle</light>
      <light>yellowLight,circle</light>
      <light>greenLight,circle</light>
    </lights>
    <stop>1,2</stop>
    <stop>1</stop>
    <go>3</go>
    <night>2</night>
    <night>0</night>
  </row>
</root>

Thanks in advance folks!

Manolo
  • 1
  • Does this answer your question? [How to read XML using XPath in Java](https://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java). Specifically for you, use `//row[@id='Germany']/lights` search instead of `getElementsByTagName`. – Parfait Nov 07 '20 at 15:03
  • Thank you this actually solved it :) – Manolo Nov 10 '20 at 11:19

0 Answers0