Tell me how in Java to output the attribute values ​​from the XML file to the console? To get these lines of output:

Ivanov 12 A red
Petrov 20 B blue

<?xml version="1.0"?> <Data> <Title> <Obj name="Ivanov" id="12" raz="A"> <Value><![CDATA[red]]></Value> </Obj> <Obj name="Petrov" id="20" raz="B"> <Value><![CDATA[blue]]></Value> </Obj> <!-- Ещё 18 Obj --> </Title> </Data> 
  • What programming language did you try to implement the task in? - Sanek Zhitnik
  • How can I output attribute values ​​from an XML file to the console in Java? - Hehabr

1 answer 1

You can use the DOM parser from the standard library, for example:

 try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(new File(fileName)); // fileName - путь до xml Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("Obj"); for (int i = 0; i < list.getLength(); i++) { Element element = (Element) list.item(i); System.out.println(element.getAttribute("name") + " " + element.getAttribute("id") + " " + element.getAttribute("raz") + " " + element.getTextContent()); } } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); }