00001 // Copyright (C) 2006 Alexis ROBERT 00002 00003 #include "xmldoc.h" 00004 #include "exceptions.h" 00005 00006 namespace freedaisy { 00007 XMLDoc::XMLDoc() { 00008 _xmldoc = NULL; 00009 createDoc(); 00010 } 00011 00012 XMLDoc::XMLDoc(std::string filename) { 00013 _xmldoc = NULL; 00014 parseFile(filename); 00015 } 00016 00017 XMLDoc::~XMLDoc() { 00018 xmlFreeDoc(_xmldoc); 00019 } 00020 00021 void XMLDoc::parseFile(std::string filename) { 00022 if (_xmldoc != NULL) // If we parse a document after createDoc() 00023 xmlFreeDoc(_xmldoc); 00024 00025 _xmldoc = xmlParseFile(filename.c_str()); 00026 if (!_xmldoc) { 00027 throw Exceptions::XMLException("Failed to load XML file"); 00028 } 00029 } 00030 00031 void XMLDoc::saveFile(std::string filename) { 00032 if (!xmlSaveFormatFile(filename.c_str(), _xmldoc, 1)) { 00033 throw Exceptions::XMLException("Failed to save XML file"); 00034 } 00035 } 00036 00037 void XMLDoc::createDoc() { 00038 _createDoc(); 00039 } 00040 00041 void XMLDoc::_createDoc() { 00042 if (_xmldoc != NULL) // Same this as parseFile() 00043 xmlFreeDoc(_xmldoc); 00044 00045 _xmldoc = xmlNewDoc((xmlChar*)"1.0"); 00046 if (!_xmldoc) { 00047 throw Exceptions::XMLException("Failed to create XML file"); 00048 } 00049 } 00050 00051 xmlDocPtr XMLDoc::getC() { 00052 return _xmldoc; 00053 } 00054 00055 std::vector<XMLNode> XMLDoc::xpathEval(std::string request) { 00056 xmlXPathContextPtr ctx; 00057 xmlXPathObjectPtr obj; 00058 xmlNodePtr cur; 00059 std::vector<XMLNode> vec; 00060 ctx = xmlXPathNewContext(_xmldoc); 00061 if (!ctx) 00062 throw Exceptions::XMLException("Failed to create XPath context"); 00063 obj = xmlXPathEvalExpression((xmlChar*)request.c_str(), ctx); 00064 if (!obj) 00065 throw Exceptions::XMLException("Failed to evaluate XPath expression"); 00066 for (int i = 0; i < obj->nodesetval->nodeNr; i++) { 00067 vec.push_back(obj->nodesetval->nodeTab[i]); 00068 } 00069 return vec; 00070 } 00071 00072 XMLNode XMLDoc::createRootNode(std::string name) { 00073 xmlNodePtr rootnode = NULL; 00074 rootnode = xmlNewTextChild((xmlNodePtr) _xmldoc, NULL, (xmlChar *) name.c_str(), NULL); 00075 if (!rootnode) 00076 throw Exceptions::XMLException("Failed to create root node"); 00077 00078 return XMLNode(rootnode); 00079 } 00080 }