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

import java.io.InputStream;
import java.util.HashMap;

import java.util.Vector;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
    public static Vector<HashMap> xmltoVector222(String xmlFile, String xpath) {
        try {
            if (!new File(xmlFile).exists()) {
                return new Vector<HashMap>();
            }
            File xmlDocument = new File(xmlFile);
            InputSource inputSource = new InputSource();
            return xmlToVector222(new FileInputStream(xmlDocument), xpath);
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Vector<HashMap>();
        }
    }

    public static Vector<HashMap> xmlToVector222(InputStream is, String xpath) {
        try {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xPath = factory.newXPath();
            InputSource inputSource = new InputSource(is);

            NodeList nodes = (NodeList) xPath.evaluate(xpath, inputSource, XPathConstants.NODESET);
            Vector<HashMap> vector = new Vector<HashMap>();

            for (int x = 0; x < nodes.getLength(); x++) {
                NodeList nodeList = nodes.item(x).getChildNodes();
                HashMap hashmap = new HashMap();
                for (int y = 0; y < nodeList.getLength(); y++) {
                    Node node = nodeList.item(y);
                    if (!node.getNodeName().equals("#text")) {
                        hashmap.put(node.getNodeName(), node.getTextContent());
                    }
                }
                vector.add(hashmap);
            }
            return vector;
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Vector();
        }
    }
}