Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Main {
    public static String getAttributeValue(File xmlfile, String nodeXpath, String attributeName)
            throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        //logger.debug("Getting the attribute value from the xml file" + xmlfile.toString());
        // get the Document object.
        Document doc = getDocument(xmlfile);

        // get the Node Object for the xpath.
        Node node = getNodeObject(nodeXpath, doc);

        NamedNodeMap attr = node.getAttributes();
        // Get the Attribute Value returned as a String
        String attributeValue = attr.getNamedItem(attributeName).getNodeValue();
        //logger.debug("Attribute name " + attributeName + " and the value is " + attributeValue);
        //logger.debug("Returning attribute value as " + attributeValue);
        return attributeValue;
    }

    private static Document getDocument(File xmlfile)
            throws ParserConfigurationException, SAXException, IOException {
        //logger.debug("Creating an Object of the Document");
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlfile);
        return doc;
    }

    private static Node getNodeObject(String xpathString, Document doc) throws XPathExpressionException {
        // Create a xptah object
        //logger.debug("Getting the node by using xpath " + xpathString);
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expr = xpath.compile(xpathString);
        Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        //logger.debug("Returning the Node object from xml file");
        return node;
    }
}