Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
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.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.net.URL;

import static javax.xml.xpath.XPathConstants.NODE;

public class Main {
    /**
     * Locates the element defined by the XPath expression in the XML file and replaces the child text with the passed value.
     * @param fileName The XML file to update.
     * @param xPathExpression An XPath expression that locates the element to update.
     * @param value The value to update the attribute to.
     */
    public static void updateElementValueInXMLFile(String fileName, String xPathExpression, String value) {
        try {
            Document document = parseXML(new File(fileName));
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression xpathExpression = xpath.compile(xPathExpression);
            Element element = (Element) xpathExpression.evaluate(document, NODE);
            element.getFirstChild().setNodeValue(value);
            writeElement(document.getDocumentElement(), fileName);
        } catch (Exception e) {
            throw new RuntimeException("Failed to extract element from:" + fileName, e);
        }
    }

    /**
     * Parses an input source and generates an XML document.
     * @param is An input source to an XML source.
     * @return An XML doucument.
     */
    public static Document parseXML(InputSource is) {
        try {
            Document doc = null;
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = documentBuilder.parse(is);
            return doc;
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse XML source", e);
        }
    }

    /**
     * Parses an input stream and generates an XML document.
     * @param is An input stream to an XML source.
     * @return An XML doucument.
     */
    public static Document parseXML(InputStream is) {
        return parseXML(new InputSource(is));
    }

    /**
     * Parses a file and generates an XML document.
     * @param file
     * @return An XML doucument.
     */
    public static Document parseXML(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return parseXML(fis);
        } catch (Exception e) {
            throw new RuntimeException("Failed to open XML file:" + file, e);
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Parses the input stream of a URL and generates an XML document.
     * @param xmlUrl The URL of the XML document.
     * @return The parsed document.
     */
    public static Document parseXML(URL xmlUrl) {
        InputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = xmlUrl.openConnection().getInputStream();
            bis = new BufferedInputStream(is);
            return parseXML(bis);
        } catch (Exception e) {
            throw new RuntimeException("Failed to read XML URL:" + xmlUrl, e);
        } finally {
            try {
                bis.close();
            } catch (Exception e) {
            }
            try {
                is.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Parses an XML string and generates an XML document.
     * @param xml The XML to parse
     * @return An XML doucument.
     */
    public static Document parseXML(CharSequence xml) {
        StringReader sr = new StringReader(xml.toString());
        return parseXML(new InputSource(sr));
    }

    /**
     * Writes an element out to a file.
     * @param element The XML element to write out.
     * @param fileName The file name to write to. Existing file is overwriten.
     */
    public static void writeElement(Element element, String fileName) {
        File file = new File(fileName);
        file.delete();
        DOMSource domSource = new DOMSource(element);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            StreamResult result = new StreamResult(fos);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, result);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException("Failed to write XML element to:" + fileName, e);
        } finally {
            try {
                fos.flush();
            } catch (Exception e) {
            }
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
}