there is

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <map> <string name="photo_link"></string> <string name="user_id">372fb7af6e0d2719d1babb6ad86dab46</string> </map> 

I want to parse the second line by its name, name = "user_id", but rather to parse its contents through the XML DOM, how to do it.

This does not work:

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(new File("/Users/k1ceargy/Desktop/testFile.xml")); Element element = document.getDocumentElement(); System.out.println(element.getAttributes().getNamedItem("user_id").getNodeValue()); 
  • Use XPath here's an example of stackoverflow.com/questions/8445408/… - Alexander Chernin
  • not exactly a convenient way, is there something else? - k1ceargy
  • @ k1ceargy, the css-selector can be more convenient than xpath and that is not always :) - gil9red

1 answer 1

One of the options for pulling the value will be through the xpath expression.

Example:

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(new File("/Users/k1ceargy/Desktop/testFile.xml")); ... XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // Или так: "map/string[@name=\"user_id\"]/text()" XPathExpression expr = xpath.compile("//*[@name=\"user_id\"]/text()"); // Если элементов несколько нужно найти указывать XPathConstants.NODESET и приводить к NodeList Node nl = (Node) expr.evaluate(document, XPathConstants.NODE); // Или nl.getTextContent() System.out.println(nl.getNodeValue()); // 372fb7af6e0d2719d1babb6ad86dab46 

You can also manually find the necessary elements through working with DOM:

 NodeList nodes = document.getElementsByTagName("string"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); Node attr = node.getAttributes().getNamedItem("name"); if (attr != null && "user_id".equals(attr.getTextContent())) { System.out.println(node.getTextContent()); // 372fb7af6e0d2719d1babb6ad86dab46 } } 

Ps. If there is a lot of code, you can always wrap it in a function:

 static String getNodeValueByName(Document doc, String name) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); String xpathStr = String.format("//*[@name=\"%s\"]/text()", name); XPathExpression expr = xpath.compile(xpathStr); Node nl = (Node) expr.evaluate(doc, XPathConstants.NODE); if (nl == null) { return null; } return nl.getNodeValue(); } ... System.out.println(getNodeValueByName(document, "photo_link")); // null System.out.println(getNodeValueByName(document, "user_id")); // 372fb7af6e0d2719d1babb6ad86dab46