Java tutorial
//package com.java2s; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.traversal.DocumentTraversal; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.traversal.NodeIterator; public class Main { private static Logger logger = Logger.getLogger(new Exception().getStackTrace()[0].getClassName()); public static Node getNode(String xmlStr, String nodeName, Map<String, String> attributesMap) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Node returnNode = null; try { DocumentBuilder db = dbf.newDocumentBuilder(); InputStream inStream = new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8)); // or InputSource inputSource = new InputSource( new StringReader( // xmlStr ) ); Document doc = db.parse(inStream); DocumentTraversal dt = (DocumentTraversal) doc; NodeIterator i = dt.createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, null, false); Node node = i.nextNode(); while (node != null) { if (node.getNodeName().equals(nodeName)) { if (attributesExist(node, attributesMap)) { returnNode = node; break; } } node = i.nextNode(); } } catch (Exception ex) { logger.error(ex); } return returnNode; } public static Node getNode(Node parentNode, String nodeName, Map<String, String> attributesMap) { Node returnNode = null; try { DocumentTraversal dt = (DocumentTraversal) parentNode.getOwnerDocument(); NodeIterator i = dt.createNodeIterator(parentNode, NodeFilter.SHOW_ELEMENT, null, false); Node node = i.nextNode(); while (node != null) { if (node.getNodeName().equals(nodeName)) { if (attributesExist(node, attributesMap)) { returnNode = node; break; } } node = i.nextNode(); } } catch (Exception ex) { logger.error(ex); } return returnNode; } public static boolean attributesExist(Node node, Map<String, String> attributesMap) { boolean exists = true; Map<String, String> nodeAttributes = new HashMap<String, String>(); for (int i = 0; i < node.getAttributes().getLength(); i++) { nodeAttributes.put(node.getAttributes().item(i).getNodeName(), node.getAttributes().item(i).getNodeValue()); } if (attributesMap == null) { return exists; } for (String attr : attributesMap.keySet()) { if (nodeAttributes.get(attr) == null) { exists = false; break; } if (!nodeAttributes.get(attr).equals(attributesMap.get(attr))) { exists = false; break; } } return exists; } }