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.FileNotFoundException;
import java.io.FileOutputStream;

import java.util.Map;
import javax.xml.parsers.DocumentBuilder;

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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    private static DocumentBuilder dombuilder = null;
    private static XPath xpath = null;

    public static void addNodeToXml(String nodeParentXpathStr, String xmlFilePath, String nodeName, String value,
            Map<String, String> attr) throws Exception {
        Document doc = null;
        if (xmlFilePath == null || nodeParentXpathStr == null || nodeName == null || nodeParentXpathStr == null)
            throw new Exception("some parameters can not be null!");
        doc = dombuilder.parse(new File(xmlFilePath));
        Node pNode = (Node) xpath.compile(nodeParentXpathStr).evaluate(doc, XPathConstants.NODE);
        if (pNode == null)
            throw new Exception("can not find the node specified in nodeParentXpathStr!");
        ;

        Element newNode = doc.createElement(nodeName);
        newNode.setTextContent(value);
        if (attr != null && !attr.isEmpty()) {
            for (String key : attr.keySet())
                newNode.setAttribute(key, attr.get(key));
        }

        pNode.appendChild(newNode);
        writeToXmlFile(doc, xmlFilePath);

    }

    private static void writeToXmlFile(Document doc, String xmlFilePath)
            throws FileNotFoundException, TransformerException {
        TransformerFactory tffactory = TransformerFactory.newInstance();
        Transformer tf = tffactory.newTransformer();
        tf.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(xmlFilePath)));
    }
}