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