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