Java XML Node Find findNodeWithAttrValue(Document doc, String elementName, String attrName, String attrValue)

Here you can find the source of findNodeWithAttrValue(Document doc, String elementName, String attrName, String attrValue)

Description

find Node With Attr Value

License

Apache License

Declaration

public static Node findNodeWithAttrValue(Document doc, String elementName, String attrName, String attrValue)
            throws Exception 

Method Source Code

//package com.java2s;
/*//from  w ww.  j a v a 2s.co  m
 * Copyright 2013 Keith D Swenson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors Include: Shamim Quader, Sameer Pradhan, Kumar Raja, Jim Farris,
 * Sandia Yang, CY Chen, Rajiv Onat, Neal Wang, Dennis Tam, Shikha Srivastava,
 * Anamika Chaudhari, Ajay Kakkar, Rajeev Rastogi
 */

import org.w3c.dom.Document;

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

public class Main {
    public static Node findNodeWithAttrValue(Document doc, String elementName, String attrName, String attrValue)
            throws Exception {
        NodeList elmts = doc.getElementsByTagNameNS("*", elementName);
        ;
        for (int i = 0; i < elmts.getLength(); i++) {
            Node n = elmts.item(i);
            if (n == null) {
                continue; // there are strange cases where it can be null
            }
            NamedNodeMap attrs = n.getAttributes();
            if (attrs != null && attrs.getLength() > 0) {
                Node attrNode = attrs.getNamedItem(attrName);
                if (attrNode != null && attrValue.equals(attrNode.getNodeValue())) {
                    return elmts.item(i);
                }
            }
        }
        return null;
    }
}

Related

  1. findNodeIndex(Node node)
  2. findNodeLong(Node node)
  3. findNodesByTagName(Document document, String tagName)
  4. findNodesNamed(Node node, String lookForName, Collection ret)
  5. findNodeValue(Node aNode, String aName)