#include "DOM.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
boolean DOMImplementation::hasFeature(String feature, String version)
{
for (int i=0; i<strlen(feature); i++)
feature[i] = toupper(feature[i]);
if ( strcmp(feature, "XML")==0 && strcmp(version, "1.0")==0 )
return true;
else return 0;
}
Node* DOMImplementation::setCurrentNode(Node* newNode)
{
Node* oldNode = getCurrentNode();
currentNode = newNode;
return oldNode;
}
boolean DOMImplementation::docParse(String xmlFile, String dtdFile)
{
if ( xmlParse(xmlFile) == NULL )
{
fprintf(stderr, "couldn't parse xml file: %s \n", xmlFile);
return 0;
}
if ( dtdParse(dtdFile) == NULL )
{
fprintf(stderr, "couldn't parse dtd file: %s \n", dtdFile);
return 0;
}
return 1;
}
//////////////////// xmlParse ////////////////////////////////
#include "callbacks.c"
DocumentFragment* DOMImplementation::xmlParse(String fileName)
{
Document* doc = getOwnerDoc();
DocumentFragment* docTree = doc->createDocumentFragment();
setCurrentNode(docTree);
depth = 0; // used for debugging expat, delete this later
XML_Parser parser = XML_ParserCreate(NULL);
XML_SetUserData(parser, this);
// set event handlers
installCallbacs(parser);
// open file
FILE* inf = fopen(fileName, "r");
if (inf == NULL)
{
fprintf(stderr, "DOMImplementation::xmlParse: cannot open file %s for reading\n", fileName);
return NULL;
}
// parse
char buf[BUFSIZ];
int done;
do
{
size_t len = fread(buf, 1, sizeof(buf), inf);
done = len < sizeof(buf);
if (!XML_Parse(parser, buf, len, done))
{
fprintf(stderr, "%s at line %d\n",
XML_ErrorString(XML_GetErrorCode(parser)),
XML_GetCurrentLineNumber(parser));
return NULL; // not parsed correctly
}
} while (!done);
XML_ParserFree(parser);
Element* docRoot = doc->createElement("xml");
doc->setDocumentElement(docRoot);
docRoot->appendChild(docTree);
return docTree;
}
///////////////// dtdParse ////////////////////////
#include "y.tab.c"
DocumentType* DOMImplementation::dtdParse(String fileName)
{
// redirect stdin to fileName
if ( freopen(fileName, "r", stdin) == NULL )
{
fprintf(stderr, "DOMImplementation::dtdParse: cannot open file: %s for reading", fileName);
return NULL;
}
// initialize global variables used by dtd parser
xmlDoc = getOwnerDoc(); // the owner of this DOMImplementation instance
docType = xmlDoc->getDoctype();
elems = docType->getElements();
attribs = docType->getAttributes();
// now parse by calling "yyparse"
// this builds the dtd structure
try { yyparse(); }
catch (DOMException& e)
{ cout << e << endl; return NULL; }
return docType;
}