Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.Element;

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

public class Main {
    /**
     * equivalent to the XPath expression './/tagName[@attrName='attrValue']'
     */
    public static Element getElementByAttributeValue(Node start, String tagName, String attrName,
            String attrValue) {
        NodeList nl = ((Element) start).getElementsByTagName(tagName);
        int l = nl.getLength();

        if (l == 0) {
            return null;
        }

        Element e = null;
        String compareValue = null;

        for (int i = 0; i < l; i++) {
            e = (Element) nl.item(i);

            if (e.getNodeType() == Node.ELEMENT_NODE) {
                compareValue = e.getAttribute(attrName);

                if (compareValue.equals(attrValue)) {
                    return e;
                }
            }
        }

        return null;
    }
}