Java tutorial
/* * JavaXmlReader.java * * Created on March 3, 2008, 9:30 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Vector; import javax.swing.JFrame; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author Lairds */ public class XMLReader { Vector<ArrayList<ArrayList<String>>> headers; Vector<Vector<String>> fromMappings; Vector<Vector<String>> toMappings; Vector<String> worksheetNames; JFrame parent; /** Creates a new instance of JavaXmlReader */ public XMLReader(String name, JFrame parent) { this.parent = parent; // parse XML file -> XML document will be build Document doc = parseFile(name); headers = new Vector<ArrayList<ArrayList<String>>>(); fromMappings = new Vector<Vector<String>>(); toMappings = new Vector<Vector<String>>(); worksheetNames = new Vector<String>(); if (doc != null) { // get root node of xml tree structure Node root = doc.getDocumentElement(); // write node and its child nodes into System.out System.out.println("Statement of XML document..."); writeDocumentToOutput(root, 0); System.out.println("... end of statement"); parseHeader(root); parseWorksheetName(root); parseMappings(root); } } public Vector<String> getTypes() { return worksheetNames; } public ArrayList<ArrayList<String>> getHeader(String type) { int index = -1; for (int i = 0; i < worksheetNames.size(); i++) { if (worksheetNames.elementAt(i).equalsIgnoreCase(type)) { index = i; } } if (index != -1) { return headers.elementAt(index); } else { return new ArrayList<ArrayList<String>>(); } } public String getWorksheetName(String type) { int index = -1; for (int i = 0; i < worksheetNames.size(); i++) { if (worksheetNames.elementAt(i).equalsIgnoreCase(type)) { index = i; } } if (index != -1) { return worksheetNames.elementAt(index); } else { return "worksheet"; } } public Vector<String> getFromMappings(String type) { int index = -1; for (int i = 0; i < worksheetNames.size(); i++) { if (worksheetNames.elementAt(i).equalsIgnoreCase(type)) { index = i; } } if (index != -1) { return fromMappings.elementAt(index); } else { return new Vector<String>(); } } public Vector<String> getToMappings(String type) { int index = -1; for (int i = 0; i < worksheetNames.size(); i++) { if (worksheetNames.elementAt(i).equalsIgnoreCase(type)) { index = i; } } if (index != -1) { return toMappings.elementAt(index); } else { return new Vector<String>(); } } private void parseHeader(Node root) { System.out.println("Parsing Header..."); Node document = null; ArrayList<String> row = new ArrayList<String>(); ArrayList<ArrayList<String>> typeHeader = new ArrayList<ArrayList<String>>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equalsIgnoreCase("DOCUMENT")) { document = child; break; } } } if (document != null) { children = document.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { System.out.println(child.getNodeName()); NodeList typeChildren = child.getChildNodes(); for (int j = 0; j < typeChildren.getLength(); j++) { Node typeChild = typeChildren.item(j); if (typeChild.getNodeType() == Node.ELEMENT_NODE) { if (typeChild.getNodeName().equalsIgnoreCase("HEADER")) { typeHeader = new ArrayList<ArrayList<String>>(); NodeList headerChildren = typeChild.getChildNodes(); for (int k = 0; k < headerChildren.getLength(); k++) { Node headerChild = headerChildren.item(k); if (headerChild.getNodeType() == Node.ELEMENT_NODE) { // New row row = new ArrayList<String>(); System.out.println(headerChild.getNodeName()); NodeList columns = headerChild.getChildNodes(); for (int l = 0; l < columns.getLength(); l++) { Node column = columns.item(l); if (column.getNodeType() == Node.ELEMENT_NODE) { // New Column System.out.println(column.getNodeName()); System.out.println(getElementValue(column).trim()); row.add(getElementValue(column).trim()); } } typeHeader.add(row); } } headers.add(typeHeader); } } } } } } else { System.err.println("XMLReader::parseHeader - No \"document\" tag found when parsing xml"); } System.out.println("...Header Parsed"); } private void parseWorksheetName(Node root) { System.out.println("Parsing Worksheet..."); Node document = null; NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equalsIgnoreCase("DOCUMENT")) { document = child; break; } } } if (document != null) { children = document.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { System.out.println(child.getNodeName()); NodeList typeChildren = child.getChildNodes(); for (int j = 0; j < typeChildren.getLength(); j++) { Node typeChild = typeChildren.item(j); if (typeChild.getNodeType() == Node.ELEMENT_NODE) { if (typeChild.getNodeName().equalsIgnoreCase("WORKSHEET_NAME")) { worksheetNames.add(getElementValue(typeChild).trim()); } } } } } } else { System.err.println("XMLReader::parseWorksheetName - No \"document\" tag found when parsing xml"); } System.out.println("...Worksheet Parsed"); } private void parseMappings(Node root) { System.out.println("Parsing Mappings..."); Node document = null; Vector<String> fromMapping = new Vector<String>(); Vector<String> toMapping = new Vector<String>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equalsIgnoreCase("DOCUMENT")) { document = child; break; } } } if (document != null) { children = document.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { System.out.println(child.getNodeName()); NodeList typeChildren = child.getChildNodes(); for (int j = 0; j < typeChildren.getLength(); j++) { Node typeChild = typeChildren.item(j); if (typeChild.getNodeType() == Node.ELEMENT_NODE) { if (typeChild.getNodeName().equalsIgnoreCase("MAPPINGS")) { fromMapping = new Vector<String>(); toMapping = new Vector<String>(); NodeList mappingsChildren = typeChild.getChildNodes(); for (int k = 0; k < mappingsChildren.getLength(); k++) { Node mappingChild = mappingsChildren.item(k); if (mappingChild.getNodeType() == Node.ELEMENT_NODE) { NodeList fromToChildren = mappingChild.getChildNodes(); for (int l = 0; l < fromToChildren.getLength(); l++) { Node fromToChild = fromToChildren.item(l); if (fromToChild.getNodeType() == Node.ELEMENT_NODE) { System.out.println(fromToChild.getNodeName()); System.out.println(getElementValue(fromToChild).trim()); if (fromToChild.getNodeName().equalsIgnoreCase("FROM")) { fromMapping.add(getElementValue(fromToChild).trim()); } else if (fromToChild.getNodeName().equalsIgnoreCase("TO")) { toMapping.add(getElementValue(fromToChild).trim()); } else { System.out.println("Unknown from to type in mappings"); } } } } } fromMappings.add(fromMapping); toMappings.add(toMapping); } } } } } } else { System.err.println("XMLReader::parseMappings - No \"document\" tag found when parsing xml"); } System.out.println("...Mappings Parsed"); } /** Parses XML file and returns XML document. * @param fileName XML file to parse * @return XML document or <B>null</B> if error occured */ private Document parseFile(String fileName) { System.out.println("Parsing XML file... " + fileName); DocumentBuilder docBuilder; Document doc = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringElementContentWhitespace(true); boolean success = true; try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { System.err.println("XMLReader::parseFile - Wrong parser configuration: " + e.getMessage()); success = false; return null; } File sourceFile = new File(fileName); try { doc = docBuilder.parse(sourceFile); } catch (SAXException e) { System.err.println("XMLReader::parseFile - Wrong XML file structure: " + e.getMessage()); success = false; return null; } catch (FileNotFoundException catcher) { System.err.println("AgencyTable::initNames - AgencyInfo.skc not Found: " + catcher.getMessage()); System.out.println("Expected XML file to be in following location: " + System.getProperty("user.dir") + "\\" + fileName + "."); } catch (IOException e) { System.err.println("XMLReader::parseFile - Could not read source file: " + e.getMessage()); success = false; } System.out.println("XML file parsed" + (success ? "" : " - but with errors")); if (!success) { System.out.println("Error reading XML file. Refer to the log file for more information."); } return doc; } /** Writes node and all child nodes into System.out * @param node XML node from from XML tree wrom which will output statement start * @param indent number of spaces used to indent output */ private void writeDocumentToOutput(Node node, int indent) { // get element name String nodeName = node.getNodeName(); // get element value String nodeValue = getElementValue(node); // get attributes of element NamedNodeMap attributes = node.getAttributes(); System.out.println(getIndentSpaces(indent) + "NodeName: " + nodeName + ", NodeValue: " + nodeValue); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); System.out.println(getIndentSpaces(indent + 2) + "AttributeName: " + attribute.getNodeName() + ", attributeValue: " + attribute.getNodeValue()); } // write all child nodes recursively NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { writeDocumentToOutput(child, indent + 2); } } } /** Returns element value * @param elem element (it is XML tag) * @return Element value otherwise empty String */ private final static String getElementValue(Node elem) { Node kid; if (elem != null) { if (elem.hasChildNodes()) { for (kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling()) { if (kid.getNodeType() == Node.TEXT_NODE) { return kid.getNodeValue(); } } } } return ""; } private String getIndentSpaces(int indent) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < indent; i++) { buffer.append(" "); } return buffer.toString(); } }