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.FileOutputStream;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
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.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static void vectorToXML222(String xmlFile, String xpath, String parentNodeName, Vector<HashMap> vector) {
        File file = new File(xmlFile);
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            Document document;
            Element rootNode;
            if (file.exists()) {
                document = documentBuilder.parse(new File(xmlFile));
                rootNode = document.getDocumentElement();
            } else {
                document = documentBuilder.newDocument();
                rootNode = document.createElement(xpath);
                document.appendChild(rootNode);
            }

            for (int x = 0; x < vector.size(); x++) {
                Element parentNode = document.createElement(parentNodeName);
                rootNode.appendChild(parentNode);
                HashMap hashmap = vector.get(x);
                Set set = hashmap.entrySet();
                Iterator i = set.iterator();

                while (i.hasNext()) {
                    Map.Entry me = (Map.Entry) i.next();
                    // System.out.println("key=" +
                    // me.getKey().toString());
                    Element em = document.createElement(me.getKey().toString());
                    em.appendChild(document.createTextNode(me.getValue().toString()));
                    parentNode.appendChild(em);
                    // System.out.println("write " +
                    // me.getKey().toString() +
                    // "="
                    // + me.getValue().toString());
                }
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            FileOutputStream fo = new FileOutputStream(xmlFile);
            StreamResult result = new StreamResult(fo);
            transformer.transform(source, result);
        } catch (Exception ex) {
            file.delete();
            ex.printStackTrace();
        }
    }
}