I'm parsing my XML File in Java with the DOM Parser/Builder. For one part of my XML Tagname it's working fine. But when I try to parse anothe Tagname, it's getting worse, because the Tagname is also used in other Tags.
XML File:
<RootTag>
<humans>
<human>
<name>Max</name>
<age>22</age>
<friends>
<friend>
<name>Peter</name>
<adress>
<street>Way down 1</street>
</adress>
</friend>
<friend>
<name>Kevin</name>
<adress>
<street>Way left 2</street>
</adress>
</friend>
</friends>
</human>
<human>
<name>Justin</name>
<age>22</age>
<friends>
<friend>
<name>Georg</name>
<adress>
<street>Way up 1</street>
</adress>
</friend>
</friends>
</human>
</humans>
<friend>
<friends>
<name>Max</name>
<numberFriends>2</numberFriends>
</friends>
<friends>
<name>Justin</name>
<numberFriends>1</numberFriends>
</friends>
</friend>
</RootTag>
Java:
public static void parse() throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File("humanFriends.xml");
Document doc = builder.parse(file);
NodeList humanL = doc.getElementsByTagName("human");
for (int j = 0; j < humanL.getLength(); j++) {
Node humanN = humanL.item(j);
if (humanN.getNodeType() == Node.ELEMENT_NODE) {
Element humanE = (Element) humanN;
String name = humanE.getElementsByTagName("name").item(0).getTextContent();
String vehicleId = humanE.getElementsByTagName("age").item(0).getTextContent();
...
}
NodeList friendsL = doc.getElementsByTagName("friends");
for (int j = 0; j < friendsL.getLength(); j++) {
Node friendsN = friendsL.item(j);
if (friendsN.getNodeType() == Node.ELEMENT_NODE) {
Element friendsE = (Element) friendsN;
String name = friendsE.getElementsByTagName("name").item(0).getTextContent();
String vehicleId = friendsE.getElementsByTagName("numberFriends").item(0).getTextContent();
here I'm getting error because parser take also friends from human Tag...
}
}
Is it possible to parse it like hierarchically or only tagsnames in specific childnodes? And is it possible to parse XML even though same tagnames in diffrent Nodes or is it a bad structur for XML?
getElementsByTagName()you get all elements with this name regardless of their hierarchy in your XML. Use XPath to get elements like/RootTag/friend/friends/numberFriendsor/RootTag/humans/human/friends/friend. Search for a tutorial or start with this: baeldung.com/java-xpath