You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XSSFExportToXml.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.extractor;
  16. import java.io.IOException;
  17. import java.io.OutputStream;
  18. import java.text.DateFormat;
  19. import java.text.SimpleDateFormat;
  20. import java.util.Comparator;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Locale;
  24. import java.util.Map;
  25. import java.util.Vector;
  26. import javax.xml.transform.OutputKeys;
  27. import javax.xml.transform.Source;
  28. import javax.xml.transform.Transformer;
  29. import javax.xml.transform.TransformerException;
  30. import javax.xml.transform.TransformerFactory;
  31. import javax.xml.transform.dom.DOMSource;
  32. import javax.xml.transform.stream.StreamResult;
  33. import javax.xml.validation.Schema;
  34. import javax.xml.validation.SchemaFactory;
  35. import javax.xml.validation.Validator;
  36. import org.apache.poi.ss.usermodel.CellType;
  37. import org.apache.poi.ss.usermodel.DateUtil;
  38. import org.apache.poi.util.DocumentHelper;
  39. import org.apache.poi.util.LocaleUtil;
  40. import org.apache.poi.util.POILogFactory;
  41. import org.apache.poi.util.POILogger;
  42. import org.apache.poi.xssf.usermodel.XSSFCell;
  43. import org.apache.poi.xssf.usermodel.XSSFMap;
  44. import org.apache.poi.xssf.usermodel.XSSFRow;
  45. import org.apache.poi.xssf.usermodel.XSSFSheet;
  46. import org.apache.poi.xssf.usermodel.XSSFTable;
  47. import org.apache.poi.xssf.usermodel.XSSFTableColumn;
  48. import org.apache.poi.xssf.usermodel.helpers.XSSFSingleXmlCell;
  49. import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr;
  50. import org.w3c.dom.Document;
  51. import org.w3c.dom.Element;
  52. import org.w3c.dom.NamedNodeMap;
  53. import org.w3c.dom.Node;
  54. import org.w3c.dom.NodeList;
  55. import org.xml.sax.SAXException;
  56. /**
  57. *
  58. * Maps an XLSX to an XML according to one of the mapping defined.
  59. *
  60. *
  61. * The output XML Schema must respect this limitations:
  62. *
  63. * <ul>
  64. * <li> all mandatory elements and attributes must be mapped (enable validation to check this)</li>
  65. *
  66. * <li> no &lt;any&gt; in complex type/element declaration </li>
  67. * <li> no &lt;anyAttribute&gt; attributes declaration </li>
  68. * <li> no recursive structures: recursive structures can't be nested more than one level </li>
  69. * <li> no abstract elements: abstract complex types can be declared but must not be used in elements. </li>
  70. * <li> no mixed content: an element can't contain simple text and child element(s) together </li>
  71. * <li> no &lt;substitutionGroup&gt; in complex type/element declaration </li>
  72. * </ul>
  73. */
  74. public class XSSFExportToXml implements Comparator<String>{
  75. private static final POILogger LOG = POILogFactory.getLogger(XSSFExportToXml.class);
  76. private XSSFMap map;
  77. private final HashMap<String, Integer> indexMap = new HashMap<>();
  78. /**
  79. * Creates a new exporter and sets the mapping to be used when generating the XML output document
  80. *
  81. * @param map the mapping rule to be used
  82. */
  83. public XSSFExportToXml(XSSFMap map) {
  84. this.map = map;
  85. }
  86. /**
  87. *
  88. * Exports the data in an XML stream
  89. *
  90. * @param os OutputStream in which will contain the output XML
  91. * @param validate if true, validates the XML against the XML Schema
  92. * @throws SAXException If validating the document fails
  93. * @throws TransformerException If transforming the document fails
  94. */
  95. public void exportToXML(OutputStream os, boolean validate) throws SAXException, TransformerException {
  96. exportToXML(os, "UTF-8", validate);
  97. }
  98. /**
  99. * Exports the data in an XML stream
  100. *
  101. * @param os OutputStream in which will contain the output XML
  102. * @param encoding the output charset encoding
  103. * @param validate if true, validates the XML against the XML Schema
  104. * @throws SAXException If validating the document fails
  105. * @throws TransformerException If transforming the document fails
  106. */
  107. public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException, TransformerException{
  108. List<XSSFSingleXmlCell> singleXMLCells = map.getRelatedSingleXMLCell();
  109. List<XSSFTable> tables = map.getRelatedTables();
  110. String rootElement = map.getCtMap().getRootElement();
  111. Document doc = DocumentHelper.createDocument();
  112. final Element root;
  113. if (isNamespaceDeclared()) {
  114. root = doc.createElementNS(getNamespace(),rootElement);
  115. } else {
  116. root = doc.createElementNS("", rootElement);
  117. }
  118. doc.appendChild(root);
  119. List<String> xpaths = new Vector<>();
  120. Map<String,XSSFSingleXmlCell> singleXmlCellsMappings = new HashMap<>();
  121. Map<String,XSSFTable> tableMappings = new HashMap<>();
  122. for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) {
  123. xpaths.add(simpleXmlCell.getXpath());
  124. singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell);
  125. }
  126. for(XSSFTable table : tables) {
  127. String commonXPath = table.getCommonXpath();
  128. xpaths.add(commonXPath);
  129. tableMappings.put(commonXPath, table);
  130. }
  131. indexMap.clear();
  132. xpaths.sort(this);
  133. indexMap.clear();
  134. for(String xpath : xpaths) {
  135. XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath);
  136. XSSFTable table = tableMappings.get(xpath);
  137. if (!xpath.matches(".*\\[.*")) {
  138. // Exports elements and attributes mapped with simpleXmlCell
  139. if (simpleXmlCell!=null) {
  140. XSSFCell cell = simpleXmlCell.getReferencedCell();
  141. if (cell!=null) {
  142. Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false);
  143. mapCellOnNode(cell,currentNode);
  144. //remove nodes which are empty in order to keep the output xml valid
  145. // FIXME: what should be done if currentNode.getTextContent() is null?
  146. if ("".equals(currentNode.getTextContent()) && currentNode.getParentNode() != null) {
  147. currentNode.getParentNode().removeChild(currentNode);
  148. }
  149. }
  150. }
  151. // Exports elements and attributes mapped with tables
  152. if (table!=null) {
  153. List<XSSFTableColumn> tableColumns = table.getColumns();
  154. XSSFSheet sheet = table.getXSSFSheet();
  155. int startRow = table.getStartCellReference().getRow() + table.getHeaderRowCount();
  156. int endRow = table.getEndCellReference().getRow();
  157. for(int i = startRow; i<= endRow; i++) {
  158. XSSFRow row = sheet.getRow(i);
  159. Node tableRootNode = getNodeByXPath(table.getCommonXpath(), doc.getFirstChild(), doc, true);
  160. short startColumnIndex = table.getStartCellReference().getCol();
  161. for (XSSFTableColumn tableColumn : tableColumns) {
  162. XSSFCell cell = row.getCell(startColumnIndex + tableColumn.getColumnIndex());
  163. if (cell != null) {
  164. XSSFXmlColumnPr xmlColumnPr = tableColumn.getXmlColumnPr();
  165. if (xmlColumnPr != null) {
  166. String localXPath = xmlColumnPr.getLocalXPath();
  167. Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false);
  168. mapCellOnNode(cell, currentNode);
  169. }
  170. }
  171. }
  172. }
  173. }
  174. } /*else {
  175. // TODO: implement filtering management in xpath
  176. }*/
  177. }
  178. boolean isValid = true;
  179. if (validate) {
  180. isValid =isValid(doc);
  181. }
  182. if (isValid) {
  183. /////////////////
  184. //Output the XML
  185. //set up a transformer
  186. TransformerFactory transfac = TransformerFactory.newInstance();
  187. Transformer trans = transfac.newTransformer();
  188. trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  189. trans.setOutputProperty(OutputKeys.INDENT, "yes");
  190. trans.setOutputProperty(OutputKeys.ENCODING, encoding);
  191. //create string from xml tree
  192. StreamResult result = new StreamResult(os);
  193. DOMSource source = new DOMSource(doc);
  194. trans.transform(source, result);
  195. }
  196. }
  197. /**
  198. * Validate the generated XML against the XML Schema associated with the XSSFMap
  199. *
  200. * @param xml the XML to validate
  201. * @return true, if document is valid
  202. * @throws SAXException If validating the document fails
  203. */
  204. private boolean isValid(Document xml) throws SAXException{
  205. try{
  206. String language = "http://www.w3.org/2001/XMLSchema";
  207. SchemaFactory factory = SchemaFactory.newInstance(language);
  208. Source source = new DOMSource(map.getSchema());
  209. Schema schema = factory.newSchema(source);
  210. Validator validator = schema.newValidator();
  211. validator.validate(new DOMSource(xml));
  212. //if no exceptions where raised, the document is valid
  213. return true;
  214. } catch(IOException e) {
  215. LOG.log(POILogger.ERROR, "document is not valid", e);
  216. }
  217. return false;
  218. }
  219. private void mapCellOnNode(XSSFCell cell, Node node) {
  220. String value ="";
  221. switch (cell.getCellType()) {
  222. case STRING: value = cell.getStringCellValue(); break;
  223. case BOOLEAN: value += cell.getBooleanCellValue(); break;
  224. case ERROR: value = cell.getErrorCellString(); break;
  225. case FORMULA:
  226. if (cell.getCachedFormulaResultType() == CellType.STRING) {
  227. value = cell.getStringCellValue();
  228. } else {
  229. if (DateUtil.isCellDateFormatted(cell)) {
  230. value = getFormattedDate(cell);
  231. } else {
  232. value += cell.getNumericCellValue();
  233. }
  234. }
  235. break;
  236. case NUMERIC:
  237. if (DateUtil.isCellDateFormatted(cell)) {
  238. value = getFormattedDate(cell);
  239. } else {
  240. value += cell.getRawValue();
  241. }
  242. break;
  243. default:
  244. }
  245. if (node instanceof Element) {
  246. Element currentElement = (Element) node;
  247. currentElement.setTextContent(value);
  248. } else {
  249. node.setNodeValue(value);
  250. }
  251. }
  252. private String removeNamespace(String elementName) {
  253. return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName;
  254. }
  255. private String getFormattedDate(XSSFCell cell) {
  256. DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
  257. sdf.setTimeZone(LocaleUtil.getUserTimeZone());
  258. return sdf.format(cell.getDateCellValue());
  259. }
  260. private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) {
  261. String[] xpathTokens = xpath.split("/");
  262. Node currentNode =rootNode;
  263. // The first token is empty, the second is the root node
  264. for(int i =2; i<xpathTokens.length;i++) {
  265. String axisName = removeNamespace(xpathTokens[i]);
  266. if (!axisName.startsWith("@")) {
  267. NodeList list =currentNode.getChildNodes();
  268. Node selectedNode = null;
  269. if (!(createMultipleInstances && i==xpathTokens.length-1) ) {
  270. // select the last child node only if we need to map to a single cell
  271. selectedNode = selectNode(axisName, list);
  272. }
  273. if (selectedNode==null) {
  274. selectedNode = createElement(doc, currentNode, axisName);
  275. }
  276. currentNode = selectedNode;
  277. } else {
  278. currentNode = createAttribute(doc, currentNode, axisName);
  279. }
  280. }
  281. return currentNode;
  282. }
  283. private Node createAttribute(Document doc, Node currentNode, String axisName) {
  284. String attributeName = axisName.substring(1);
  285. NamedNodeMap attributesMap = currentNode.getAttributes();
  286. Node attribute = attributesMap.getNamedItem(attributeName);
  287. if (attribute==null) {
  288. attribute = doc.createAttributeNS("", attributeName);
  289. attributesMap.setNamedItem(attribute);
  290. }
  291. return attribute;
  292. }
  293. private Node createElement(Document doc, Node currentNode, String axisName) {
  294. Node selectedNode;
  295. if (isNamespaceDeclared()) {
  296. selectedNode =doc.createElementNS(getNamespace(),axisName);
  297. } else {
  298. selectedNode = doc.createElementNS("", axisName);
  299. }
  300. currentNode.appendChild(selectedNode);
  301. return selectedNode;
  302. }
  303. private Node selectNode(String axisName, NodeList list) {
  304. Node selectedNode = null;
  305. for(int j=0;j<list.getLength();j++) {
  306. Node node = list.item(j);
  307. if (node.getNodeName().equals(axisName)) {
  308. selectedNode=node;
  309. break;
  310. }
  311. }
  312. return selectedNode;
  313. }
  314. private boolean isNamespaceDeclared() {
  315. String schemaNamespace = getNamespace();
  316. return schemaNamespace!=null && !schemaNamespace.isEmpty();
  317. }
  318. private String getNamespace() {
  319. return map.getCTSchema().getNamespace();
  320. }
  321. /**
  322. * Compares two xpaths to define an ordering according to the XML Schema
  323. *
  324. */
  325. @Override
  326. public int compare(String leftXpath, String rightXpath) {
  327. Node xmlSchema = map.getSchema();
  328. String[] leftTokens = leftXpath.split("/");
  329. String[] rightTokens = rightXpath.split("/");
  330. String samePath = "";
  331. int minLength = leftTokens.length< rightTokens.length? leftTokens.length : rightTokens.length;
  332. Node localComplexTypeRootNode = xmlSchema;
  333. for(int i =1;i <minLength; i++) {
  334. String leftElementName = leftTokens[i];
  335. String rightElementName = rightTokens[i];
  336. if (leftElementName.equals(rightElementName)) {
  337. samePath += "/" + leftElementName;
  338. localComplexTypeRootNode = getComplexTypeForElement(leftElementName, xmlSchema, localComplexTypeRootNode);
  339. } else {
  340. return indexOfElementInComplexType(samePath, leftElementName, rightElementName,localComplexTypeRootNode);
  341. }
  342. }
  343. return 0;
  344. }
  345. private int indexOfElementInComplexType(String samePath,String leftElementName,String rightElementName,Node complexType) {
  346. if(complexType == null) {
  347. return 0;
  348. }
  349. int i = 0;
  350. Node node = complexType.getFirstChild();
  351. final String leftWithoutNamespace = removeNamespace(leftElementName);
  352. int leftIndexOf = getAndStoreIndex(samePath, leftWithoutNamespace);
  353. final String rightWithoutNamespace = removeNamespace(rightElementName);
  354. int rightIndexOf = getAndStoreIndex(samePath, rightWithoutNamespace);
  355. while (node != null && (rightIndexOf==-1||leftIndexOf==-1)) {
  356. if (node instanceof Element && "element".equals(node.getLocalName())) {
  357. String elementValue = getNameOrRefElement(node).getNodeValue();
  358. if (elementValue.equals(leftWithoutNamespace)) {
  359. leftIndexOf = i;
  360. indexMap.put(samePath+"/"+leftWithoutNamespace, leftIndexOf);
  361. }
  362. if (elementValue.equals(rightWithoutNamespace)) {
  363. rightIndexOf = i;
  364. indexMap.put(samePath+"/"+rightWithoutNamespace, rightIndexOf);
  365. }
  366. }
  367. i++;
  368. node = node.getNextSibling();
  369. }
  370. if(leftIndexOf == -1 || rightIndexOf == -1) {
  371. return 0;
  372. }
  373. return Integer.compare(leftIndexOf, rightIndexOf);
  374. }
  375. private int getAndStoreIndex(String samePath,String withoutNamespace) {
  376. String withPath = samePath+"/"+withoutNamespace;
  377. return indexMap.getOrDefault(withPath, -1);
  378. }
  379. private Node getNameOrRefElement(Node node) {
  380. Node returnNode = node.getAttributes().getNamedItem("ref");
  381. if(returnNode != null) {
  382. return returnNode;
  383. }
  384. return node.getAttributes().getNamedItem("name");
  385. }
  386. private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) {
  387. String elementNameWithoutNamespace = removeNamespace(elementName);
  388. String complexTypeName = getComplexTypeNameFromChildren(localComplexTypeRootNode, elementNameWithoutNamespace);
  389. // Note: we expect that all the complex types are defined at root level
  390. Node complexTypeNode = null;
  391. // FIXME: what should be done if complexTypeName is null?
  392. if (!"".equals(complexTypeName)) {
  393. complexTypeNode = getComplexTypeNodeFromSchemaChildren(xmlSchema, null, complexTypeName);
  394. }
  395. return complexTypeNode;
  396. }
  397. private String getComplexTypeNameFromChildren(Node localComplexTypeRootNode,
  398. String elementNameWithoutNamespace) {
  399. if(localComplexTypeRootNode == null) {
  400. return "";
  401. }
  402. Node node = localComplexTypeRootNode.getFirstChild();
  403. String complexTypeName = "";
  404. while (node != null) {
  405. if ( node instanceof Element && "element".equals(node.getLocalName())) {
  406. Node nameAttribute = getNameOrRefElement(node);
  407. if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) {
  408. Node complexTypeAttribute = node.getAttributes().getNamedItem("type");
  409. if (complexTypeAttribute!=null) {
  410. complexTypeName = complexTypeAttribute.getNodeValue();
  411. break;
  412. }
  413. }
  414. }
  415. node = node.getNextSibling();
  416. }
  417. return complexTypeName;
  418. }
  419. private Node getComplexTypeNodeFromSchemaChildren(Node xmlSchema, Node complexTypeNode,
  420. String complexTypeName) {
  421. Node node = xmlSchema.getFirstChild();
  422. while (node != null) {
  423. if ( node instanceof Element) {
  424. if ("complexType".equals(node.getLocalName())) {
  425. Node nameAttribute = getNameOrRefElement(node);
  426. if (nameAttribute.getNodeValue().equals(complexTypeName)) {
  427. Node sequence = node.getFirstChild();
  428. while(sequence != null) {
  429. if ( sequence instanceof Element) {
  430. final String localName = sequence.getLocalName();
  431. if ("sequence".equals(localName) || "all".equals(localName)) {
  432. complexTypeNode = sequence;
  433. break;
  434. }
  435. }
  436. sequence = sequence.getNextSibling();
  437. }
  438. if (complexTypeNode!=null) {
  439. break;
  440. }
  441. }
  442. }
  443. }
  444. node = node.getNextSibling();
  445. }
  446. return complexTypeNode;
  447. }
  448. }