Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

public class Main {
    private static Logger logger = Logger.getLogger(new Exception().getStackTrace()[0].getClassName());

    public static String setValueXPath(String srcXmlString, String xPath, String newVal) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false); // never forget this!
        int i, j;
        Document doc = null;
        DocumentBuilder builder = null;
        try {
            builder = domFactory.newDocumentBuilder();
            doc = builder.parse(new ByteArrayInputStream(srcXmlString.getBytes()));
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(xPath);

            Object result = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList xPathNodes = (NodeList) result;
            logger.debug("xpath result count: " + xPathNodes.getLength());
            logger.debug(xPathNodes.item(0).getNodeName() + " = " + xPathNodes.item(0).getTextContent());

            // get list of all nodes in doc
            NodeList nodes = doc.getElementsByTagName("*");
            // iterate through all the nodes
            for (i = 0; i < xPathNodes.getLength(); i++) {
                // for each node in xpath result - traverse through all nodes in
                // doc to find match
                for (j = 0; j < nodes.getLength(); j++) {
                    if (nodes.item(j).isSameNode(xPathNodes.item(i))) {
                        logger.debug("Old value " + i + ": " + xPathNodes.item(i).getNodeName() + " = "
                                + xPathNodes.item(i).getTextContent());
                        nodes.item(j).setTextContent(newVal);
                        logger.debug("New value " + i + ": " + xPathNodes.item(i).getNodeName() + " = "
                                + xPathNodes.item(i).getTextContent());
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            // ex.printStackTrace();
        }
        return getW3CXmlFromDoc(doc);
    }

    private static String getW3CXmlFromDoc(Document doc) {
        String xmlString = null;
        Transformer transformer;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
            // transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // yes,
            // no
            transformer.setOutputProperty(OutputKeys.INDENT, "no");

            // initialize StreamResult with File object to save to file
            StreamResult xmlStream = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, xmlStream);
            xmlString = xmlStream.getWriter().toString();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

        return xmlString;
    }
}