get XML Value By Name - Java XML

Java examples for XML:DOM

Description

get XML Value 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 name = "java2s.com";
        System.out.println(getXMLValueByName(xmlFilePath, name));
    }//from  w  w  w.  jav  a  2  s. com

    public static String getXMLValueByName(String xmlFilePath, String name) {
        String returnValue = "No Value!";
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                .newInstance();
        try {
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            InputStream is = new FileInputStream(xmlFilePath);
            Document doc = builder.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(name)) {
                            returnValue = node.getTextContent().trim();
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return returnValue;
    }
}

Related Tutorials