From: Ugo Cei Date: Wed, 21 Oct 2009 07:15:37 +0000 (+0000) Subject: Removed @author tag. X-Git-Tag: REL_3_6~96 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=9a51ddc536b650d9920d4bd712b6eebd4df3b130;p=poi.git Removed @author tag. Dealt with exceprions properly. General reformatting. git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@827907 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java index 04272e36cc..66209ed612 100644 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java +++ b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java @@ -74,441 +74,435 @@ import org.xml.sax.SAXException; *
  • no mixed content: an element can't contain simple text and child element(s) together
  • *
  • no <substitutionGroup> in complex type/element declaration
  • * - * - * @author Roberto Manicardi */ public class XSSFExportToXml implements Comparator{ - private XSSFMap map; - - /** - * Creates a new exporter and sets the mapping to be used when generating the XML output document - * - * @param map the mapping rule to be used - */ - public XSSFExportToXml(XSSFMap map) { - this.map = map; - } - - /** - * - * Exports the data in an XML stream - * - * @param os OutputStream in which will contain the output XML - * @param validate if true, validates the XML againts the XML Schema - * @throws SAXException - */ - public void exportToXML(OutputStream os, boolean validate) throws SAXException{ - exportToXML(os,"UTF-8", validate); - } - - private Document getEmptyDocument() throws ParserConfigurationException{ - - DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); - Document doc = docBuilder.newDocument(); - - return doc; - } + private XSSFMap map; + + /** + * Creates a new exporter and sets the mapping to be used when generating the XML output document + * + * @param map the mapping rule to be used + */ + public XSSFExportToXml(XSSFMap map) { + this.map = map; + } + + /** + * + * Exports the data in an XML stream + * + * @param os OutputStream in which will contain the output XML + * @param validate if true, validates the XML againts the XML Schema + * @throws SAXException + * @throws TransformerException + * @throws ParserConfigurationException + */ + public void exportToXML(OutputStream os, boolean validate) throws SAXException, ParserConfigurationException, TransformerException { + exportToXML(os, "UTF-8", validate); + } + + private Document getEmptyDocument() throws ParserConfigurationException{ + + DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); + Document doc = docBuilder.newDocument(); + + return doc; + } - /** - * Exports the data in an XML stream - * - * @param os OutputStream in which will contain the output XML - * @param encoding the output charset encoding - * @param validate if true, validates the XML againts the XML Schema - * @throws SAXException - * @throws InvalidFormatException - */ - public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException{ - List singleXMLCells = map.getRelatedSingleXMLCell(); - List tables = map.getRelatedTables(); + /** + * Exports the data in an XML stream + * + * @param os OutputStream in which will contain the output XML + * @param encoding the output charset encoding + * @param validate if true, validates the XML againts the XML Schema + * @throws SAXException + * @throws ParserConfigurationException + * @throws TransformerException + * @throws InvalidFormatException + */ + public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException, ParserConfigurationException, TransformerException{ + List singleXMLCells = map.getRelatedSingleXMLCell(); + List
    tables = map.getRelatedTables(); - String rootElement = map.getCtMap().getRootElement(); + String rootElement = map.getCtMap().getRootElement(); - try{ + Document doc = getEmptyDocument(); - Document doc = getEmptyDocument(); + Element root = null; - Element root = null; + if (isNamespaceDeclared()) { + root=doc.createElementNS(getNamespace(),rootElement); + } else { + root=doc.createElement(rootElement); + } + doc.appendChild(root); - if (isNamespaceDeclared()) { - root=doc.createElementNS(getNamespace(),rootElement); - } else { - root=doc.createElement(rootElement); - } - doc.appendChild(root); + List xpaths = new Vector(); + Map singleXmlCellsMappings = new HashMap(); + Map tableMappings = new HashMap(); - List xpaths = new Vector(); - Map singleXmlCellsMappings = new HashMap(); - Map tableMappings = new HashMap(); + for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) { + xpaths.add(simpleXmlCell.getXpath()); + singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell); + } + for(Table table : tables) { + String commonXPath = table.getCommonXpath(); + xpaths.add(commonXPath); + tableMappings.put(commonXPath, table); + } - for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) { - xpaths.add(simpleXmlCell.getXpath()); - singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell); - } - for(Table table : tables) { - String commonXPath = table.getCommonXpath(); - xpaths.add(commonXPath); - tableMappings.put(commonXPath, table); - } + Collections.sort(xpaths,this); - Collections.sort(xpaths,this); + for(String xpath : xpaths) { - for(String xpath : xpaths) { + XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath); + Table table = tableMappings.get(xpath); - XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath); - Table table = tableMappings.get(xpath); + if (!xpath.matches(".*\\[.*")) { - if (!xpath.matches(".*\\[.*")) { + // Exports elements and attributes mapped with simpleXmlCell + if (simpleXmlCell!=null) { + XSSFCell cell = simpleXmlCell.getReferencedCell(); + if (cell!=null) { + Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false); + STXmlDataType.Enum dataType = simpleXmlCell.getXmlDataType(); + mapCellOnNode(cell,currentNode,dataType); + } + } - // Exports elements and attributes mapped with simpleXmlCell - if (simpleXmlCell!=null) { - XSSFCell cell = simpleXmlCell.getReferencedCell(); - if (cell!=null) { - Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false); - STXmlDataType.Enum dataType = simpleXmlCell.getXmlDataType(); - mapCellOnNode(cell,currentNode,dataType); - } - } + // Exports elements and attributes mapped with tables + if (table!=null) { - // Exports elements and attributes mapped with tables - if (table!=null) { + List tableColumns = table.getXmlColumnPrs(); - List tableColumns = table.getXmlColumnPrs(); + XSSFSheet sheet = table.getXSSFSheet(); - XSSFSheet sheet = table.getXSSFSheet(); + int startRow = table.getStartCellReference().getRow(); + // In mappings created with Microsoft Excel the first row contains the table header and must be skipped + startRow +=1; - int startRow = table.getStartCellReference().getRow(); - // In mappings created with Microsoft Excel the first row contains the table header and must be skipped - startRow +=1; + int endRow = table.getEndCellReference().getRow(); - int endRow = table.getEndCellReference().getRow(); + for(int i = startRow; i<= endRow; i++) { + XSSFRow row = sheet.getRow(i); - for(int i = startRow; i<= endRow; i++) { - XSSFRow row = sheet.getRow(i); + Node tableRootNode = getNodeByXPath(table.getCommonXpath(),doc.getFirstChild(),doc,true); - Node tableRootNode = getNodeByXPath(table.getCommonXpath(),doc.getFirstChild(),doc,true); + short startColumnIndex = table.getStartCellReference().getCol(); + for(int j = startColumnIndex; j<= table.getEndCellReference().getCol();j++) { + XSSFCell cell = row.getCell(j); + if (cell!=null) { + XSSFXmlColumnPr pointer = tableColumns.get(j-startColumnIndex); + String localXPath = pointer.getLocalXPath(); + Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false); + STXmlDataType.Enum dataType = pointer.getXmlDataType(); - short startColumnIndex = table.getStartCellReference().getCol(); - for(int j = startColumnIndex; j<= table.getEndCellReference().getCol();j++) { - XSSFCell cell = row.getCell(j); - if (cell!=null) { - XSSFXmlColumnPr pointer = tableColumns.get(j-startColumnIndex); - String localXPath = pointer.getLocalXPath(); - Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false); - STXmlDataType.Enum dataType = pointer.getXmlDataType(); + mapCellOnNode(cell,currentNode,dataType); + } - mapCellOnNode(cell,currentNode,dataType); - } + } - } + } - } + } + } else { + // TODO: implement filtering management in xpath + } + } - } - } else { - // TODO: implement filtering management in xpath - } - } + boolean isValid = true; + if (validate) { + isValid =isValid(doc); + } - boolean isValid = true; - if (validate) { - isValid =isValid(doc); - } + if (isValid) { - if (isValid) { + ///////////////// + //Output the XML - ///////////////// - //Output the XML + //set up a transformer + TransformerFactory transfac = TransformerFactory.newInstance(); + Transformer trans = transfac.newTransformer(); + trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + trans.setOutputProperty(OutputKeys.INDENT, "yes"); + trans.setOutputProperty(OutputKeys.ENCODING, encoding); - //set up a transformer - TransformerFactory transfac = TransformerFactory.newInstance(); - Transformer trans = transfac.newTransformer(); - trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - trans.setOutputProperty(OutputKeys.INDENT, "yes"); - trans.setOutputProperty(OutputKeys.ENCODING, encoding); + //create string from xml tree - //create string from xml tree + StreamResult result = new StreamResult(os); + DOMSource source = new DOMSource(doc); + trans.transform(source, result); - StreamResult result = new StreamResult(os); - DOMSource source = new DOMSource(doc); - trans.transform(source, result); + } + } - } - }catch(ParserConfigurationException e) { - e.printStackTrace(); - }catch(TransformerException e) { - e.printStackTrace(); - } + /** + * Validate the generated XML against the XML Schema associated with the XSSFMap + * + * @param xml the XML to validate + * @return + */ + private boolean isValid(Document xml) throws SAXException{ + boolean isValid = false; + try{ + String language = XMLConstants.W3C_XML_SCHEMA_NS_URI; + SchemaFactory factory = SchemaFactory.newInstance(language); - } + Source source = new DOMSource(map.getSchema()); + Schema schema = factory.newSchema(source); + Validator validator = schema.newValidator(); + validator.validate(new DOMSource(xml)); + //if no exceptions where raised, the document is valid + isValid=true; - /** - * Validate the generated XML against the XML Schema associated with the XSSFMap - * - * @param xml the XML to validate - * @return - */ - private boolean isValid(Document xml) throws SAXException{ - boolean isValid = false; - try{ - String language = XMLConstants.W3C_XML_SCHEMA_NS_URI; - SchemaFactory factory = SchemaFactory.newInstance(language); - Source source = new DOMSource(map.getSchema()); - Schema schema = factory.newSchema(source); - Validator validator = schema.newValidator(); - validator.validate(new DOMSource(xml)); - //if no exceptions where raised, the document is valid - isValid=true; + } catch(IOException e) { + e.printStackTrace(); + } + return isValid; + } - } catch(IOException e) { - e.printStackTrace(); - } - return isValid; - } + private void mapCellOnNode(XSSFCell cell, Node node, STXmlDataType.Enum outputDataType) { + String value =""; + switch (cell.getCellType()) { - private void mapCellOnNode(XSSFCell cell, Node node, STXmlDataType.Enum outputDataType) { + case XSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; + case XSSFCell.CELL_TYPE_BOOLEAN: value += cell.getBooleanCellValue(); break; + case XSSFCell.CELL_TYPE_ERROR: value = cell.getErrorCellString(); break; + case XSSFCell.CELL_TYPE_FORMULA: value = cell.getStringCellValue(); break; + case XSSFCell.CELL_TYPE_NUMERIC: value += cell.getRawValue(); break; + default: ; - String value =""; - switch (cell.getCellType()) { + } + if (node instanceof Element) { + Element currentElement = (Element) node; + currentElement.setTextContent(value); + } else { + node.setNodeValue(value); + } + } - case XSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; - case XSSFCell.CELL_TYPE_BOOLEAN: value += cell.getBooleanCellValue(); break; - case XSSFCell.CELL_TYPE_ERROR: value = cell.getErrorCellString(); break; - case XSSFCell.CELL_TYPE_FORMULA: value = cell.getStringCellValue(); break; - case XSSFCell.CELL_TYPE_NUMERIC: value += cell.getRawValue(); break; - default: ; + private String removeNamespace(String elementName) { + return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName; + } - } - if (node instanceof Element) { - Element currentElement = (Element) node; - currentElement.setTextContent(value); - } else { - node.setNodeValue(value); - } - } - private String removeNamespace(String elementName) { - return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName; - } + private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) { + String[] xpathTokens = xpath.split("/"); - private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) { - String[] xpathTokens = xpath.split("/"); + Node currentNode =rootNode; + // The first token is empty, the second is the root node + for(int i =2; i rightIndex) { - result = 1; - } - } else { - // NOTE: the xpath doesn't match correctly in the schema - } - } - } - - return result; - } - - private int indexOfElementInComplexType(String elementName,Node complexType) { - - NodeList list = complexType.getChildNodes(); - int indexOf = -1; - - for(int i=0; i< list.getLength();i++) { - Node node = list.item(i); - if (node instanceof Element) { - if (node.getLocalName().equals("element")) { - Node nameAttribute = node.getAttributes().getNamedItem("name"); - if (nameAttribute.getNodeValue().equals(removeNamespace(elementName))) { - indexOf = i; - break; - } - - } - } - } - return indexOf; - } - - private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) { - Node complexTypeNode = null; - - String elementNameWithoutNamespace = removeNamespace(elementName); - - - NodeList list = localComplexTypeRootNode.getChildNodes(); - String complexTypeName = ""; - - - - for(int i=0; i< list.getLength();i++) { - Node node = list.item(i); - if ( node instanceof Element) { - if (node.getLocalName().equals("element")) { - Node nameAttribute = node.getAttributes().getNamedItem("name"); - if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) { - Node complexTypeAttribute = node.getAttributes().getNamedItem("type"); - if (complexTypeAttribute!=null) { - complexTypeName = complexTypeAttribute.getNodeValue(); - break; - } - } - } - } - } - // Note: we expect that all the complex types are defined at root level - if (!"".equals(complexTypeName)) { - NodeList complexTypeList = xmlSchema.getChildNodes(); - for(int i=0; i< complexTypeList.getLength();i++) { - Node node = list.item(i); - if ( node instanceof Element) { - if (node.getLocalName().equals("complexType")) { - Node nameAttribute = node.getAttributes().getNamedItem("name"); - if (nameAttribute.getNodeValue().equals(complexTypeName)) { - - NodeList complexTypeChildList =node.getChildNodes(); - for(int j=0; j rightIndex) { + result = 1; + } + } else { + // NOTE: the xpath doesn't match correctly in the schema + } + } + } + + return result; + } + + private int indexOfElementInComplexType(String elementName,Node complexType) { + + NodeList list = complexType.getChildNodes(); + int indexOf = -1; + + for(int i=0; i< list.getLength();i++) { + Node node = list.item(i); + if (node instanceof Element) { + if (node.getLocalName().equals("element")) { + Node nameAttribute = node.getAttributes().getNamedItem("name"); + if (nameAttribute.getNodeValue().equals(removeNamespace(elementName))) { + indexOf = i; + break; + } + + } + } + } + return indexOf; + } + + private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) { + Node complexTypeNode = null; + + String elementNameWithoutNamespace = removeNamespace(elementName); + + + NodeList list = localComplexTypeRootNode.getChildNodes(); + String complexTypeName = ""; + + + + for(int i=0; i< list.getLength();i++) { + Node node = list.item(i); + if ( node instanceof Element) { + if (node.getLocalName().equals("element")) { + Node nameAttribute = node.getAttributes().getNamedItem("name"); + if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) { + Node complexTypeAttribute = node.getAttributes().getNamedItem("type"); + if (complexTypeAttribute!=null) { + complexTypeName = complexTypeAttribute.getNodeValue(); + break; + } + } + } + } + } + // Note: we expect that all the complex types are defined at root level + if (!"".equals(complexTypeName)) { + NodeList complexTypeList = xmlSchema.getChildNodes(); + for(int i=0; i< complexTypeList.getLength();i++) { + Node node = list.item(i); + if ( node instanceof Element) { + if (node.getLocalName().equals("complexType")) { + Node nameAttribute = node.getAttributes().getNamedItem("name"); + if (nameAttribute.getNodeValue().equals(complexTypeName)) { + + NodeList complexTypeChildList =node.getChildNodes(); + for(int j=0; j