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 updateNodeToXml(String nodeXpathStr, String xmlFilePath, String value,
            Map<String, String> attr) throws Exception {
        Document doc = null;
        if (xmlFilePath == null || nodeXpathStr == null)
            throw new Exception("some parameters can not be null!");
        doc = dombuilder.parse(new File(xmlFilePath));
        Node pNode = (Node) xpath.compile(nodeXpathStr).evaluate(doc, XPathConstants.NODE);
        if (pNode == null)
            throw new Exception("can not find the node specified in nodeXpathStr!");
        ;
        pNode.setTextContent(value);

        if (attr != null && !attr.isEmpty()) {
            for (String key : attr.keySet())
                ((Element) pNode).setAttribute(key, attr.get(key));
        }

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