XdmfCoreReader.cpp 29.6 KB
Newer Older
Kenneth Leiter's avatar
Kenneth Leiter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfCoreReader.cpp                                                  */
/*                                                                           */
/*  Author:                                                                  */
/*     Kenneth Leiter                                                        */
/*     kenneth.leiter@arl.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2011 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/
23

24
#include <libxml/uri.h>
25
#include <libxml/xpointer.h>
26
#include <libxml/xmlreader.h>
27
#include "boost/tokenizer.hpp"
28
#include <map>
29
#include <sstream>
30
#include <cstring>
31 32
#include <utility>
#include "XdmfArray.hpp"
33 34
#include "XdmfArrayType.hpp"
#include "XdmfHDF5Controller.hpp"
35 36
#include "XdmfCoreItemFactory.hpp"
#include "XdmfCoreReader.hpp"
37
#include "XdmfError.hpp"
38
#include "XdmfItem.hpp"
39
#include "XdmfSystemUtils.hpp"
40

41 42 43 44 45 46 47
/**
 * PIMPL
 */
class XdmfCoreReader::XdmfCoreReaderImpl {

public:

48
  XdmfCoreReaderImpl(const shared_ptr<const XdmfCoreItemFactory> itemFactory,
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
                     const XdmfCoreReader * const coreReader) :
    mCoreReader(coreReader),
    mItemFactory(itemFactory)
  {
  };

  ~XdmfCoreReaderImpl()
  {
  };

  void
  closeFile()
  {
    mXPathMap.clear();
    xmlXPathFreeContext(mXPathContext);
64 65 66 67 68 69
    for(std::map<std::string, xmlDocPtr>::const_iterator iter = 
	  mDocuments.begin(); iter != mDocuments.end(); ++iter) {
      xmlFreeDoc(iter->second);
    }
    mDocuments.clear();
    
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    xmlCleanupParser();
  }

  void
  openFile(const std::string & filePath)
  {
    mXMLDir = XdmfSystemUtils::getRealPath(filePath);
    size_t index = mXMLDir.find_last_of("/\\");
    if(index != std::string::npos) {
      mXMLDir = mXMLDir.substr(0, index + 1);
    }

    mDocument = xmlReadFile(filePath.c_str(), NULL, 0);

    if(mDocument == NULL) {
85 86 87 88 89 90 91 92
      try {
        XdmfError::message(XdmfError::FATAL,
                           "xmlReadFile could not read " + filePath +
                           " in XdmfCoreReader::XdmfCoreReaderImpl::openFile");
      }
      catch (XdmfError e) {
        throw e;
      }
93 94
    }

95 96
    mDocuments.insert(std::make_pair((char*)mDocument->URL, mDocument));

97 98 99 100
    mXPathContext = xmlXPtrNewContext(mDocument, NULL, NULL);
    mXPathMap.clear();
  }

101 102 103 104 105 106
  void
  parse(const std::string & lightData) 
  {
    mDocument = xmlParseDoc((const xmlChar*)lightData.c_str());
                               
    if(mDocument == NULL) {
107 108 109 110 111 112 113 114
      try {
        XdmfError::message(XdmfError::FATAL,
                           "xmlReadFile could not parse passed light data string"
                           " in XdmfCoreReader::XdmfCoreReaderImpl::parse");
      }
      catch (XdmfError e) {
        throw e;
      }
115 116
    }

117
    //    mDocuments.insert(std::make_pair((char*)mDocument->URL, mDocument));
118 119 120 121
    mXPathContext = xmlXPtrNewContext(mDocument, NULL, NULL);
    mXPathMap.clear();
  }

122 123 124 125 126
  /**
   * Constructs XdmfItems for all nodes in currNode's tree.
   * XdmfItems are constructed by recursively calling this function for all
   * children of currNode.
   */
127
  std::vector<shared_ptr<XdmfItem> >
128 129
  read(xmlNodePtr currNode)
  {
130
    std::vector<shared_ptr<XdmfItem> > myItems;
131 132 133 134 135

    while(currNode != NULL) {
      if(currNode->type == XML_ELEMENT_NODE) {
        if(xmlStrcmp(currNode->name, (xmlChar*)"include") == 0) {
          // Deal with proper reading of XIncludes
136 137 138 139

          xmlChar * xpointer = NULL;
          xmlChar * href = NULL;

140 141 142 143 144
          xmlAttrPtr currAttribute = currNode->properties;
          while(currAttribute != NULL) {
            if(xmlStrcmp(currAttribute->name, (xmlChar*)"xpointer") == 0) {
              xpointer = currAttribute->children->content;
            }
145 146 147 148 149 150 151 152
            if(xmlStrcmp(currAttribute->name, (xmlChar*)"href") == 0) {
              href = currAttribute->children->content;
            }
            currAttribute = currAttribute->next;
          }

          xmlXPathContextPtr context = mXPathContext;
          if(href) {
153
	    xmlDocPtr document;
154
            xmlChar * filePath = xmlBuildURI(href, mDocument->URL);
155 156 157 158 159 160 161 162 163 164
	    std::map<std::string, xmlDocPtr>::const_iterator iter = 
	      mDocuments.find((char*)filePath);
	    if(iter == mDocuments.end()) {
	      document = xmlReadFile((char*)filePath, NULL, 0);
	      mDocuments.insert(std::make_pair((char*)document->URL, document));
	    }
	    else {
	      document = iter->second;
	    }

165
            context = xmlXPtrNewContext(document, NULL, NULL);           
166
          }
167

168
          if(xpointer) {
169 170 171 172
            xmlXPathObjectPtr result = xmlXPtrEval(xpointer, context);
            if(result && !xmlXPathNodeSetIsEmpty(result->nodesetval)) {
              for(int i=0; i<result->nodesetval->nodeNr; ++i) {
                this->readSingleNode(result->nodesetval->nodeTab[i],
173 174 175
                                     myItems);
              }
            }
176 177 178 179 180
            xmlXPathFreeObject(result);
          }

          if(href) {
            xmlXPathFreeContext(context);
181
          }
182

183
        }
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
        else if (xmlStrcmp(currNode->name, (xmlChar*)"Function") == 0) {
          //function handling goes here
          xmlNodePtr childNode = currNode->children;

          std::string arraySubType = "";
          //get Array Subtype, if any
          xmlAttrPtr currAttribute = currNode->properties;
          while (currAttribute != NULL) {
            if (xmlStrcmp(currAttribute->name, (xmlChar*)"Type") == 0 ) {
              arraySubType = (char*)currAttribute->children->content;
              break;//uses the first type found
            }
          }

          std::string expressionToParse = "";

          while (childNode != NULL) {
            if (xmlStrcmp(childNode->name, (xmlChar*)"Expression") == 0){
              //store expression
              xmlAttrPtr childAttribute = childNode->properties;
              while (childAttribute != NULL) {
                if(xmlStrcmp(childAttribute->name, (xmlChar*)"Value") == 0) {
                  expressionToParse = (char*)childAttribute->children->content;
                  break;
                }
                childAttribute = childAttribute->next;
              }
              break;
            }
            childNode = childNode->next;
          }

          if (expressionToParse.compare("") == 0) {
217 218 219 220 221 222 223
            try {
              XdmfError::message(XdmfError::FATAL,
                "Error: No Expression in Function");
            }
            catch (XdmfError e) {
              throw e;
            }
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
          }

          //two seperate loops to allow for different orders and multiple variable sets
          childNode = currNode->children;

          std::map<std::string, shared_ptr<XdmfArray> > variableCollection;
          while (childNode != NULL) {
            if (xmlStrcmp(childNode->name, (xmlChar*)"Variable") == 0) {
              //store child variables
              xmlNodePtr childVariable = childNode->children;

              while (childVariable != NULL) {
                if (xmlStrcmp(childVariable->name, (xmlChar*)"DataItem") == 0) {
                  xmlAttrPtr childAttribute = childVariable->properties;
                  std::string childKey = "";
                  shared_ptr<XdmfArray> childArray = XdmfArray::New();
                  std::string dataString = "";
                  shared_ptr<const XdmfArrayType> dataType;
                  xmlChar * childXPointer = NULL;
                  xmlChar * childhref = NULL;
                  std::string childhdf5 = "";
                  std::map<std::string, std::string> typeMap;

                  while (childAttribute != NULL) {
                    //the variable type of the array
                    if (xmlStrcmp(childAttribute->name, (xmlChar*)"DataType") == 0) {
                      typeMap["DataType"] = (char*)childAttribute->children->content;
                    }
                    //the precision of the variable type (only used for long and double)
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"Precision") == 0) {
                      typeMap["Precision"] = (char*)childAttribute->children->content;
                    }
                    //the key or mapped string for the variable
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"Key") == 0) {
                      childKey = (char*)childAttribute->children->content;
                    }
                    //text based xml data
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"Value") == 0) {
                      dataString = (char*)childAttribute->children->content;
                    }
                    //an x pointer to another XdmfArray
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"XPointer") == 0) {
                      childXPointer = childAttribute->children->content;
                    }
                    //used in conjunction with Xpointers to reference objects in a different file
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"href") == 0) {
                      childhref = childAttribute->children->content;
                    }
                    //path to hdf5 data sets and the dimensions of those sets
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"hdf5") == 0) {
                      childhdf5 = (char*)childAttribute->children->content;
                    }
                    childAttribute = childAttribute->next;
                  }

                  if (typeMap["DataType"].compare("Float") == 0) {
                    if (typeMap["Precision"].compare("8") == 0) {
                      dataType = XdmfArrayType::Float64();
                    }
                    else {
                      dataType = XdmfArrayType::Float32();
                    }
                  }
                  else if (typeMap["DataType"].compare("Int") == 0) {
                    if (typeMap["Precision"].compare("8") == 0) {
                      dataType = XdmfArrayType::Int64();
                    }
                    else {
                      dataType = XdmfArrayType::Int32();
                    }
                  }
                  else if (typeMap["DataType"].compare("String") == 0) {
                    dataType = XdmfArrayType::String();
                  }
                  else if (typeMap["DataType"].compare("Char") == 0) {
                    dataType = XdmfArrayType::Int8();
                  }
                  else if (typeMap["DataType"].compare("Short") == 0) {
                    dataType = XdmfArrayType::Int16();
                  }
                  else if (typeMap["DataType"].compare("UChar") == 0) {
                    dataType = XdmfArrayType::UInt8();
                  }
                  else if (typeMap["DataType"].compare("UShort") == 0) {
                    dataType = XdmfArrayType::UInt16();
                  }
                  else if (typeMap["DataType"].compare("UInt") == 0) {
                    dataType = XdmfArrayType::UInt32();
                  }
                  else {
                    dataType = XdmfArrayType::Uninitialized();
                  }

                  //if xpointer grab item at that location
                  if (childXPointer) {
                    xmlXPathContextPtr context = mXPathContext;

                    if(childhref) {
                      xmlDocPtr document;
                      xmlChar * filePath = xmlBuildURI(childhref, mDocument->URL);
                      std::map<std::string, xmlDocPtr>::const_iterator iter =
                        mDocuments.find((char*)filePath);
                      if(iter == mDocuments.end()) {
                        document = xmlReadFile((char*)filePath, NULL, 0);
                        mDocuments.insert(std::make_pair((char*)document->URL, document));
                      }
                      else {
                        document = iter->second;
                      }
                      context = xmlXPtrNewContext(document, NULL, NULL);
                    }

                    if(childXPointer) {
                      xmlXPathObjectPtr result = xmlXPtrEval(childXPointer, context);
                      if(result && !xmlXPathNodeSetIsEmpty(result->nodesetval)) {
                        for(int i=0; i<result->nodesetval->nodeNr; ++i) {
                          //there should only be one item being returned here
                          //place into a new vector
                          std::vector<shared_ptr<XdmfItem> > pointedItems;
                          this->readSingleNode(result->nodesetval->nodeTab[i], pointedItems);
                          try {
                            childArray = shared_dynamic_cast<XdmfArray>(pointedItems[0]);//try to cast it as an array
                          }
                          catch (...) {//if that doesn't work throw an error
348 349 350 351 352 353 354
                            try {
                              XdmfError::message(XdmfError::FATAL,
                                                 "Error: Variable not Equivalent to an Array");//because we should only be working with arrays
                            }
                            catch (XdmfError e) {
                              throw e;
                            }
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
                          }
                        }
                      }
                      xmlXPathFreeObject(result);
                    }

                    if(childhref) {
                      xmlXPathFreeContext(context);
                    }
                  }
                  //if hdf5 create controllers and attach it
                  else if (childhdf5.compare("") != 0) {
                    //parse the hdf5 controllers
                    std::vector<std::string> controllerParts;
                    //split the content based on "|" characters
                    size_t barSplit = 0;
                    std::string splitString(childhdf5);
                    std::string subcontent;

                    while (barSplit != std::string::npos) {
                      barSplit = 0;
                      barSplit = splitString.find_first_of("|", barSplit);
                      if (barSplit == std::string::npos) {
                        subcontent = splitString;
                      }
                      else {
                        subcontent = splitString.substr(0, barSplit);
                        splitString = splitString.substr(barSplit+1);
                        barSplit++;
                      }
                      controllerParts.push_back(subcontent);
                    }

                    //insert those controllers into the childArray
                    int hdf5step = 2;
390
                    for (unsigned int i = 0; i < controllerParts.size(); i = i + hdf5step) {
391 392
                      size_t colonLocation = controllerParts[i].find(":");
                      if(colonLocation == std::string::npos) {
393 394 395 396 397 398 399 400 401
                        try {
                          XdmfError::message(XdmfError::FATAL,
                                             "':' not found in function variable content in "
                                             "read -- double check an HDF5 "
                                             "data set is specified for the file");
                        }
                        catch (XdmfError e) {
                          throw e;
                        }
402 403 404 405 406 407
                      }

                      std::string hdf5Path = controllerParts[i].substr(0, colonLocation);
                      std::string dataSetPath = controllerParts[i].substr(colonLocation+1);
                      std::vector<unsigned int> contentDims;

408
                      if (i + 1 < controllerParts.size()){
409 410 411 412 413 414 415 416 417
                        //this is the string that contains the dimensions
                        boost::tokenizer<> dimtokens(controllerParts[i + 1]);
                        for(boost::tokenizer<>::const_iterator iter = dimtokens.begin();
                            iter != dimtokens.end();
                            ++iter) {
                          contentDims.push_back(atoi((*iter).c_str()));
                        }
                        hdf5step = 2;//if this works then the dimension content should be skipped over
                      }
418
                      else {//if it fails then it means that the next content is not a dimension string
419 420
                        //in this case an error should be thrown, formatting error
                        //because there is no base array to pull dimensions from
421 422 423 424 425 426 427
                        try {
                          XdmfError::message(XdmfError::FATAL,
                                             "Error: Improper HDF5 Format");
                        }
                        catch (XdmfError e) {
                          throw e;
                        }
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
                      }

                      childArray->insert(XdmfHDF5Controller::New(hdf5Path,
                                                                 dataSetPath,
                                                                 dataType,
                                                                 std::vector<unsigned int>(contentDims.size(), 0),
                                                                 std::vector<unsigned int>(contentDims.size(), 1),
                                                                 contentDims,
                                                                 contentDims));
                    }
                  }
                  //if xml parse strait to insert
                  else if (dataString.compare("") != 0) {
                    //parse the data into tokens
                    childArray->initialize(dataType, 0);
                    unsigned int index = 0;
                    boost::char_separator<char> sep(" \t\n");
                    boost::tokenizer<boost::char_separator<char> > tokens(dataString, sep);
                    if(dataType == XdmfArrayType::String()) {
                      for(boost::tokenizer<boost::char_separator<char> >::const_iterator
                          iter = tokens.begin();
                          iter != tokens.end();
                          ++iter, ++index) {
                        //insert those tokens into the childArray
                        childArray->insert(index, *iter);
                      }
                    }
                    else {
                      for(boost::tokenizer<boost::char_separator<char> >::const_iterator
                          iter = tokens.begin();
                          iter != tokens.end();
                          ++iter, ++index) {
                        //insert those tokens into the childArray
                        childArray->insert(index, atof((*iter).c_str()));
                      }
                    }
                  }

                  //parse the value into the array
                  if (childKey.compare("") != 0){
                    if (variableCollection.find(childKey) != variableCollection.end()) {
469 470 471 472 473 474 475
                      try {
                        XdmfError::message(XdmfError::WARNING,
                                           "Warning: Variable Redefined");
                      }
                      catch (XdmfError e) {
                        throw e;
                      }
476 477 478 479 480
                    }
                    childArray->read();
                    variableCollection[childKey] = childArray;
                  }
                  else {
481 482 483 484 485 486 487
                    try {
                      XdmfError::message(XdmfError::WARNING,
                                         "Warning: Value Unpaired to Key");
                    }
                    catch (XdmfError e) {
                      throw e;
                    }
488 489 490 491 492 493 494
                  }
                }
                childVariable = childVariable->next;
              }
            }
            childNode = childNode->next;
          }
495 496 497 498 499 500 501
          shared_ptr<XdmfArray> parsedArray = shared_ptr<XdmfArray>();
          try {
            parsedArray = XdmfArray::evaluateExpression(expressionToParse, variableCollection);
          }
          catch (XdmfError e) {
            throw e;
          }
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
          //the properties and children aren't really needed to generate the object, but the factory still requires them.
          std::map<std::string, std::string> newArrayProperties;
          std::vector<shared_ptr<XdmfItem> > newArrayChildren;
          shared_ptr<XdmfArray> returnArray = XdmfArray::New();

          if (arraySubType.compare("") == 0) {//if no type is specified an array is generated
            arraySubType = "DataItem";
          }

          //this should generate an item that corresponds to the tag provided, the casting ensures that it is a subtype of array
          //using a factory to be able to build things outside of core
          returnArray = shared_dynamic_cast<XdmfArray>(mItemFactory->createItem(
                                                       arraySubType,
                                                       newArrayProperties,
                                                       newArrayChildren));

          if (!returnArray) {//if the specified tag fails to generate an item then reclass as an array
            arraySubType = "DataItem";
            returnArray = shared_dynamic_cast<XdmfArray>(mItemFactory->createItem(
                                                         arraySubType,
                                                         newArrayProperties,
                                                         newArrayChildren));
          }

          returnArray->insert(0, parsedArray, 0, parsedArray->getSize());
          myItems.push_back(returnArray);
        }
529 530
        else {
          // Normal reading
531 532 533 534 535 536
          try {
            this->readSingleNode(currNode, myItems);
          }
          catch (XdmfError e) {
            throw e;
          }
537 538 539 540 541 542 543 544 545 546 547 548 549 550
        }
      }
      currNode = currNode->next;
    }
    return myItems;
  }

  /**
   * Reads a single xmlNode into an XdmfItem object in memory. The constructed
   * XdmfItem is added to myItems and an entry is added mapping the xmlNodePtr
   * to the new XdmfItem in the mXPathMap.
   */
  void
  readSingleNode(const xmlNodePtr currNode,
551
                 std::vector<shared_ptr<XdmfItem> > & myItems)
552
  {
553
    //check to see if the node is already in the Xpath
554
    std::map<xmlNodePtr, shared_ptr<XdmfItem> >::const_iterator iter =
555
      mXPathMap.find(currNode);
556
    if(iter != mXPathMap.end()) {//if it is grab it from the previously stored items
557 558
      myItems.push_back(iter->second);
    }
559
    else {//otherwise, generate it from the node
560
      std::map<std::string, std::string> itemProperties;
561 562

      xmlNodePtr childNode = currNode->children;
563
      if (XdmfArray::ItemTag.compare((char *)currNode->name) == 0) {
564
	unsigned int childContentIndex = 0;
565 566 567
        while(childNode != NULL) {
          if(childNode->type == XML_TEXT_NODE && childNode->content) {
            const char * content = (char*)childNode->content;
568 569 570



571 572 573 574 575
            
            // determine if content is whitespace
            bool whitespace = true;
            
            const char * contentPtr = content;
576
            //step through to end of pointer
577
            while(contentPtr != NULL) {
578
              //if not a whitespace character, break
579 580 581 582 583 584 585
              if(!isspace(*contentPtr++)) {
                whitespace = false;
                break;
              }
            }
            
            if(!whitespace) {
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
              if (childContentIndex == 0) {
                itemProperties.insert(std::make_pair("XMLDir", mXMLDir));
              }

              //split the content based on "|" characters
              size_t barSplit = 0;
              std::string splitString(content);
              std::string subcontent;
              while (barSplit != std::string::npos) {
		barSplit = 0;
                barSplit = splitString.find_first_of("|", barSplit);
                if (barSplit == std::string::npos) {
                  subcontent = splitString;
                }
                else {
                  subcontent = splitString.substr(0, barSplit);
                  splitString = splitString.substr(barSplit+1);
                  barSplit++;
                }
                std::stringstream contentString;
                contentString << "Content" << childContentIndex;
                itemProperties.insert(std::make_pair(contentString.str(), subcontent));
		childContentIndex++;
              }
610 611
            }
          }
612
          childNode = childNode->next;
613
        }
614
      }
615 616
    
 
617 618
      xmlAttrPtr currAttribute = currNode->properties;
      while(currAttribute != NULL) {
619 620
        itemProperties.insert(std::make_pair((char *)currAttribute->name,
                                             (char *)currAttribute->children->content));
621 622
        currAttribute = currAttribute->next;
      }
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
      try {
        const std::vector<shared_ptr<XdmfItem> > childItems =
          this->read(currNode->children);
        shared_ptr<XdmfItem> newItem = 
          mItemFactory->createItem((const char *)currNode->name,
                                   itemProperties,
                                   childItems);
      
        if(newItem == NULL) {
          try {
            XdmfError::message(XdmfError::FATAL, 
                               "mItemFactory failed to createItem in "
                               "XdmfCoreReader::XdmfCoreReaderImpl::readSingleNode");
          }
          catch (XdmfError e) {
            throw e;
          }
        }
        newItem->populateItem(itemProperties, childItems, mCoreReader);
        myItems.push_back(newItem);
        mXPathMap.insert(std::make_pair(currNode, newItem));
      }
      catch (XdmfError e) {
        throw e;
647 648 649 650 651 652
      }
    }
  }

  void
  readPathObjects(const std::string & xPath,
653
                  std::vector<shared_ptr<XdmfItem> > & myItems)
654 655 656 657 658
  {
    xmlXPathObjectPtr xPathObject =
      xmlXPathEvalExpression((xmlChar*)xPath.c_str(), mXPathContext);
    if(xPathObject && xPathObject->nodesetval) {
      for(int i=0; i<xPathObject->nodesetval->nodeNr; ++i) {
659 660 661 662 663 664
        try {
          this->readSingleNode(xPathObject->nodesetval->nodeTab[i], myItems);
        }
        catch (XdmfError e) {
          throw e;
        }
665 666 667 668 669 670
      }
    }
    xmlXPathFreeObject(xPathObject);
  }

  xmlDocPtr mDocument;
671
  std::map<std::string, xmlDocPtr> mDocuments;
672
  const XdmfCoreReader * const mCoreReader;
673
  const shared_ptr<const XdmfCoreItemFactory> mItemFactory;
674 675
  std::string mXMLDir;
  xmlXPathContextPtr mXPathContext;
676
  std::map<xmlNodePtr, shared_ptr<XdmfItem> > mXPathMap;
677 678
};

679
XdmfCoreReader::XdmfCoreReader(const shared_ptr<const XdmfCoreItemFactory> itemFactory) :
680
  mImpl(new XdmfCoreReaderImpl(itemFactory, this))
681 682 683 684 685
{
}

XdmfCoreReader::~XdmfCoreReader()
{
686
  delete mImpl;
687 688
}

689 690 691
shared_ptr<XdmfItem >
XdmfCoreReader::parse(const std::string & lightData) const
{
692 693 694 695 696 697
  try {
    mImpl->parse(lightData);
  }
  catch (XdmfError e) {
    throw e;
  }
698
  const xmlNodePtr currNode = xmlDocGetRootElement(mImpl->mDocument);
699
  std::vector<shared_ptr<XdmfItem> > toReturn;
700 701 702 703 704 705 706 707 708
  try {
    if(mImpl->mItemFactory->createItem((const char*)currNode->name,
                                       std::map<std::string, std::string>(),
                                       std::vector<shared_ptr<XdmfItem> >()) == NULL) {
      toReturn = mImpl->read(currNode->children);
    }
    else {
      toReturn = mImpl->read(currNode);
    }
709
  }
710 711
  catch (XdmfError e) {
    throw e;
712
  }
713 714 715 716
  mImpl->closeFile();
  return(toReturn[0]);
}

717
std::vector<shared_ptr<XdmfItem> >
718
XdmfCoreReader::readItems(const std::string & filePath) const
719
{
720 721 722 723 724 725 726 727 728 729 730 731
  try {
    mImpl->openFile(filePath);
    const xmlNodePtr currNode = xmlDocGetRootElement(mImpl->mDocument);
    const std::vector<shared_ptr<XdmfItem> > toReturn =
      mImpl->read(currNode->children);
    mImpl->closeFile();
    return toReturn;
  }
  catch (XdmfError e) {
    throw e;
  }

732 733
}

734
shared_ptr<XdmfItem>
735
XdmfCoreReader::read(const std::string & filePath) const
736
{
737 738 739 740 741 742 743 744 745
  try {
    const std::vector<shared_ptr<XdmfItem> > toReturn = readItems(filePath);
    if (toReturn.size() == 0) {
      return(shared_ptr<XdmfItem>());
    }
    return(toReturn[0]);
  }
  catch (XdmfError e) {
    throw e;
746
  }
747
}
748

749
std::vector<shared_ptr<XdmfItem> >
750 751
XdmfCoreReader::read(const std::string & filePath,
                     const std::string & xPath) const
752
{
753 754 755 756 757 758 759 760 761
  try {
    mImpl->openFile(filePath);
    std::vector<shared_ptr<XdmfItem> > toReturn = this->readPathObjects(xPath);
    mImpl->closeFile();
    return toReturn;
  }
  catch (XdmfError e) {
    throw e;
  }
762
}
763

764
std::vector<shared_ptr<XdmfItem> >
765
XdmfCoreReader::readPathObjects(const std::string & xPath) const
766
{
767
  std::vector<shared_ptr<XdmfItem> > toReturn;
768 769 770 771 772 773
  try {
    mImpl->readPathObjects(xPath, toReturn);
  }
  catch (XdmfError e) {
    throw e;
  }
774
  return toReturn;
775 776
}