00001 #include "SDXCSVStreamReader.h"
00002 #include "SDXContentHandler.h"
00003
00004 using namespace std;
00005 using namespace SDX;
00006 using namespace SDX::Formats;
00007
00008 CsvStreamReader::CsvStreamReader(istream* iStream, ContentHandler* contentHandler) :
00009 StreamReader(iStream, contentHandler)
00010 {
00011
00012 }
00013
00014 void CsvStreamReader::setFieldNames(std::vector<std::string> fieldNames){
00015 m_fieldNames = fieldNames;
00016 }
00017
00018 void CsvStreamReader::setRowName(std::string rowName){
00019 m_rowName = rowName;
00020 }
00021
00022 void CsvStreamReader::startProcessing(){
00023 m_fieldNamesSet = !m_fieldNames.empty();
00024 }
00025
00026 bool CsvStreamReader::processLine(string& line){
00027 if(line.empty())
00028 return true;
00029
00030 if(m_fieldNamesSet)
00031 m_contentHandler->startNode(m_rowName);
00032
00033 int curField = 0;
00034 while(!line.empty()){
00035 if(m_fieldNamesSet && curField >= m_fieldNames.size())
00036 m_contentHandler->startNode("Unknown");
00037 else if(m_fieldNamesSet)
00038 m_contentHandler->startNode(m_fieldNames[curField++]);
00039
00040 char firstChar = line.at(0);
00041 if(firstChar == ','){
00042 line.erase(0, 1);
00043 m_contentHandler->writeAttribute("", "");
00044 m_contentHandler->endNode();
00045 } else if(firstChar == '"'){
00046 size_t nextQuote = findNextQuote(line);
00047 if(m_fieldNamesSet){
00048 m_contentHandler->writeAttribute("", line.substr(1, nextQuote - 1));
00049 m_contentHandler->endNode();
00050 } else
00051 m_fieldNames.push_back(line.substr(1, nextQuote - 1));
00052
00053 line.erase(0, nextQuote + 1);
00054 if(!line.empty())
00055 line.erase(0, 1);
00056 } else {
00057 size_t firstComma = line.find_first_of(",");
00058
00059 if(m_fieldNamesSet){
00060 m_contentHandler->writeAttribute("", line.substr(0, firstComma));
00061 m_contentHandler->endNode();
00062 } else
00063 m_fieldNames.push_back(line.substr(0, firstComma));
00064
00065 if(firstComma != string::npos)
00066 line.erase(0, firstComma + 1);
00067 else
00068 break;
00069 }
00070 }
00071
00072 if(m_fieldNamesSet)
00073 m_contentHandler->endNode();
00074 else
00075 m_fieldNamesSet = true;
00076
00077 return true;
00078 }
00079
00080 size_t CsvStreamReader::findNextQuote(string& line){
00081 int startIndex = 0;
00082 if(line.at(0) == '"')
00083 startIndex = 1;
00084
00085 size_t nextQuote = line.find_first_of(line.at(0), startIndex);
00086 return nextQuote;
00087 }