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.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
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.Node;
import org.xml.sax.SAXException;

public class Main {
    public static void setNodeTextValue(File xmlfile, String nodeXpath, String textValue) throws Exception {
        //logger.debug("Setting the Text value of the node");

        // get the Document object.
        Document doc = getDocument(xmlfile);

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

        // Get the Attribute Value returned as a String
        node.setTextContent(textValue);
        //logger.debug("Node name " + nodeXpath + " and the text to Set is " + textValue);
        wirteXmlFile(doc, xmlfile);
        //logger.debug("Node value changed successfully in xml file " + xmlfile.toString());
    }

    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;
    }

    private static void wirteXmlFile(Document doc, File file) throws TransformerException {
        // Write the content into xml file
        //logger.debug("Changes are done in xml file, Writing to the XML file");
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file);
        transformer.transform(source, result);
    }
}