Java XML Element Get by Attribute findElementWithAttributes(Node node, String tagName, Collection attrs)

Here you can find the source of findElementWithAttributes(Node node, String tagName, Collection attrs)

Description

find Element With Attributes

License

Open Source License

Declaration

public static Element findElementWithAttributes(Node node, String tagName, Collection<String> attrs) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Collection;

import org.w3c.dom.Element;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Element findElementWithAttributes(Node node, String tagName, Collection<String> attrs) {
        Element result = null;//from  w  w w  . ja va 2  s.  c  om
        NodeList nodeList = node.getChildNodes();
        if (nodeList == null) {
            return result;
        }
        for (int i = 0; i < nodeList.getLength(); ++i) {
            Element element = checkIfElement(nodeList.item(i), tagName);
            if (element != null) {
                boolean match = true;
                for (String attrName : attrs) {
                    if (!element.hasAttribute(attrName)) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    result = element;
                    break;
                }
            }
        }
        return result;
    }

    public static final Element checkIfElement(Node node) {
        Element result = null;
        if (isElement(node)) {
            result = (Element) node;
        }
        return result;
    }

    public static final Element checkIfElement(Node node, String tag) {
        Element result = null;
        if (isElement(node)) {
            Element tmp = (Element) node;
            if (tag == null || tmp.getTagName().equals(tag)) {
                result = tmp;
            }
        }
        return result;
    }

    public static boolean isElement(Node node) {
        return node.getNodeType() == Node.ELEMENT_NODE;
    }
}

Related

  1. findComponent(Element element, String attributeValue)
  2. findElement(Element element, String elementName, String attributeValue)
  3. findElement(Element parent, String elementNS, String elementName, String attrName, String attrValue)
  4. findElementByAttribute(final NodeList list, final String name, final String value)
  5. findElementsByAttribute(Element node, String tagName, String attrName, List attrValues)
  6. findElementWithNameAttribute(Element parent, String name)
  7. findElementWithUniqueAttribute(Element root, String elementName, String attribute, String attributeValue)
  8. findNode(Node node, String attr, String value)
  9. findNodeByAttributeValue(NodeList nodeList, String attributeName, String attributeValue)