Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.File;

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 {
    private final static String getElement(String filePath, String key) throws Exception {

        String value = null;

        try {

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            File xmlFile = new File(filePath);

            Document document = documentBuilder.parse(xmlFile);

            Element resourcesElement = document.getDocumentElement();
            resourcesElement.normalize();

            NodeList strings = resourcesElement.getChildNodes();

            int stringsCount = strings.getLength();

            for (int i = 0; i < stringsCount; i++) {

                Node node = strings.item(i);

                short nodeType = node.getNodeType();

                if (nodeType == Node.ELEMENT_NODE) {

                    Element element = (Element) node;

                    String attribute = element.getAttribute("name");

                    if (attribute.equals(key)) {

                        value = element.getTextContent();
                    }
                }
            }

        } catch (Exception ex) {

            throw ex;
        }

        return value;
    }
}