get XML Node Attribute By Name - Java XML

Java examples for XML:XML Attribute

Description

get XML Node Attribute By Name

Demo Code


//package com.java2s;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xmlFilePath = "java2s.com";
        String nodeName = "java2s.com";
        String attributeName = "java2s.com";
        System.out.println(getNodeAttributeByName(xmlFilePath, nodeName,
                attributeName));/*www .  j a  va 2 s .c  om*/
    }

    public static String getNodeAttributeByName(String xmlFilePath,
            String nodeName, String attributeName) {
        String returnVal = "No value!";
        DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory
                .newInstance();
        try {

            DocumentBuilder domBuilder = domBuilderFactory
                    .newDocumentBuilder();
            InputStream is = new FileInputStream(xmlFilePath);
            Document doc = domBuilder.parse(is);
            Element root = doc.getDocumentElement();
            NodeList nodes = root.getChildNodes();
            if (nodes != null) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        String test = node.getNodeName();
                        if (test.equals(nodeName)) {
                            returnVal = node.getAttributes()
                                    .getNamedItem(attributeName)
                                    .getNodeValue();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnVal;
    }
}

Related Tutorials