There is xml with a lot of elements. Some elements have the same name but the child elements may differ.
The xml structure is approximately as follows:

<tag1> <tag2>data1</tag2> <tag3>data2</tag3> <tag4> <tag5> <tag6>value1</tag6> <tag7>value2</tag7> <tag8>value3</tag8> <tag9>value4</tag9> <tag10>value5</tag10> </tag5> <tag5> <tag6>value6</tag6> <tag7>value7</tag7> <tag8>value8</tag8> <tag9>value9</tag9> <tag10>value10</tag10> </tag5> </tag4> </tag1> 

You must get the value of tag9 if tag10 satisfies a certain condition

Java code:

 try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(new File("someXML.xml")); Element root = doc.getDocumentElement(); NodeList tagFiveNodeList = root.getElementsByTagName("tag5"); for (int i = 0; i < tagFiveNodeList.getLength(); i++) { Node tagFiveNode = tagFiveNodeList.item(i); NodeList tagFiveChildNodes = tagFiveNode.getChildNodes(); for (int j = 0; j < tagFiveChildNodes.getLength(); j++) { Node tagFiveChildNode = tagFiveChildNodes.item(j); // проверка условия if (tagFiveChildNode.getTextContent().contains("Some Text")) { } } } } catch (Exception e) { e.printStackTrace(); } 

After checking for content in any of the child tags of a particular text, I want to get the value of another tag from the same list of child tags.
How can I do it?

    1 answer 1

    You must cast Node to Element

     Element tagFiveNode = (Element)tagFiveNodeList.item(i); 

    And then use the getElementsByTagName method

     if (tagFiveNode.getElementsByTagName('tag10').item(0).getTextContent()....) value = tagFiveNode.getElementsByTagName('tag9').item(0).getTextContent(); 

    This is provided that such nodes exist. If they can be absent, then you need to check the size of the collection returned by the getElementsByTagName method.

    • The thing is, tagFiveNode is a Node, and Node, like NodeList, does not have a getElementsByTagName method. - Slava Near
    • @SlavaNear Casting Element tagFiveNode = (Element)tagFiveNodeList.item(i); - Anton Shchyrov
    • Thank you. Everything Works - Slava Near