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

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

    public static String setAttribute(String xmlStr, String tagName, String attrName, String newValue) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false); // never forget this!
        int i, j;
        Document doc = null;
        DocumentBuilder builder = null;

        StringWriter stringOut = new StringWriter();
        try {
            builder = domFactory.newDocumentBuilder();
            doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
            // Get the root element
            Node rootNode = doc.getFirstChild();
            NodeList nodeList = doc.getElementsByTagName(tagName);
            if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) {
                logger.error("Either node " + tagName + " or attribute " + attrName + " not found.");
            } else {
                logger.debug("value of " + tagName + " attribute: " + attrName + " = "
                        + nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue());
                nodeList.item(0).getAttributes().getNamedItem(attrName).setNodeValue(newValue);

                // write the content into xml file
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(stringOut);
                // StreamResult result = new StreamResult(new File(filepath));
                transformer.transform(source, result);
                logger.debug("Updated XML: \n" + stringOut.toString());
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        return stringOut.toString();
    }
}