Bug 55864

Summary: [PATCH] NullPointerException: XSSFImportFromXML.importFromXML() does not support optional elements
Product: POI Reporter: Thomas Kessler <thomas.kessler>
Component: XSSFAssignee: POI Developers List <dev>
Status: RESOLVED FIXED    
Severity: major CC: thomas.kessler
Priority: P2 Keywords: PatchAvailable
Version: 3.9-FINAL   
Target Milestone: ---   
Hardware: PC   
OS: All   
Attachments: ZIP containing an XML Schema with optional element, an XML file that validates against this schema and an Excel file with XML Maps using 'mapping.xsd'
Patch containing a bugfix and a unit test

Description Thomas Kessler 2013-12-09 22:37:34 UTC
Created attachment 31102 [details]
ZIP containing an XML Schema with optional element, an XML file that validates against this schema and an Excel file with XML Maps using 'mapping.xsd'

Please see the contents of the zip file attached to this bug...

The XML Schema file 'mapping.xsd' contains an optional element:
 <xs:element name="OptionalRating" type="xs:decimal" minOccurs="0"/>

The XML file 'data.xml' validates successfully against 'mapping.xsd'. It does not contain the element 'OptionalRating'.

Importing 'data.xml' into an Excel file with XML maps using 'mapping.xsd' with XSSFImportFromXML.importFromXML(xmlInputString) fails with a NullPointerException because the code assumes that all elements declared in the XML Schema file must also be present in the XML data file (which is not necessarily the case if elements are declared optional.

The exception occurs on the following code line in method "XSSFImportFromXML.importFromXML(xmlInputString)":
 Node result = (Node) xpath.evaluate(xpathString, doc, XPathConstants.NODE);
 // result can be null with optional nodes!
 String textContent = result.getTextContent(); // NPE on 'result' access

A unit test to reproduce this exception could look like this:
 InputStream xlsxInput = getResourceAsStream("excelWithMapping.xlsx");
 InputStream xmlInput = getResourceAsStream("data.xml");
 String xml = IOUtils.toString(xmlInput);
 XSSFWorkbook wb = openWorkbook(xlsxInput);
 XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map");
 XSSFImportFromXML importer = new XSSFImportFromXML(map);
 importer.importFromXML(xml); // throws NPE


Additional info:
- used POI version: 3.9
- used Excel version: 2010
Comment 1 Thomas Kessler 2014-01-20 17:05:09 UTC
Created attachment 31237 [details]
Patch containing a bugfix and a unit test

The patch makes it possible to import XML into an Excel file which is mapped with a schema containing optional elements (minOccurs="0").
The patch also contains a new unit test (all other tests still work).
Comment 2 Dominik Stadler 2014-10-21 15:56:58 UTC
Thanks for the patch, this is now applied as r1633404.