/* XML parser example using libxml * Author: Olivier Dadoun * olivier@dadoun.net, 2006 * Last modified 08.02.2006 *See www.solfxml.org for documentations and examples **/ #include #include #include #include #include #include void parseDoc(char *docname); void parseInfo(xmlDocPtr doc, xmlNodePtr cur); void parseDetec(xmlDocPtr doc, xmlNodePtr cur); //////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { char temp[256]; if (argc <= 1) { printf("Usage: %s XML file name \n", argv[0]); return 0; } sprintf(temp,"%s",argv[1]); parseDoc(temp); return 0; } void parseDoc(char *docname) { xmlDocPtr doc; xmlNodePtr cur; doc = xmlParseFile(docname); if (doc == NULL ) { fprintf(stderr,"Document not parsed successfully. \n"); return; } cur = xmlDocGetRootElement(doc); //GO the first node if (cur == NULL) { fprintf(stderr,"empty document\n"); xmlFreeDoc(doc); return; } //test the xml format, must be start by example if (xmlStrcmp(cur->name, (const xmlChar *) "detector")) { fprintf(stderr,"XML document of the wrong type, root node != detector\n"); fprintf(stderr,"Check your XML file :(\n"); xmlFreeDoc(doc); return; } //go to the childrens nodes cur = cur->xmlChildrenNode; while (cur != NULL) { xmlChar *infoName; xmlChar *infoTitle; xmlChar *infoAuthor; if ((!xmlStrcmp(cur->name, (const xmlChar *)"info"))) { infoName = xmlGetProp(cur,"name"); infoTitle = xmlGetProp(cur,"title"); infoAuthor = xmlGetProp(cur,"author"); printf("%s \t %s \t %s \n",infoName,infoTitle,infoAuthor); parseInfo(doc,cur); } if ((!xmlStrcmp(cur->name, (const xmlChar *)"detec"))) parseDetec(doc, cur); cur = cur->next; } xmlFreeDoc(doc); return; } void parseInfo(xmlDocPtr doc, xmlNodePtr cur) { cur = cur->xmlChildrenNode; while (cur != NULL) { if((!xmlStrcmp(cur->name,(const xmlChar *)"comment"))) printf("%s\n",xmlNodeListGetString(doc,cur->xmlChildrenNode,1)); cur = cur->next; } return; } void parseDetec(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *detectorMaterialName; xmlChar *zplaneRmin; xmlChar *zplaneRmax; xmlChar *layerId; xmlChar *layerInner_r; xmlChar *layerOuter_z; cur = cur->xmlChildrenNode; while (cur != NULL) { if(!xmlStrcmp(cur->name,(const xmlChar *)"material")) { detectorMaterialName= xmlGetProp(cur,"name"); printf("DetectMatName %s\n",detectorMaterialName); } if(!xmlStrcmp(cur->name,(const xmlChar *)"zplane")) { zplaneRmin = xmlGetProp(cur,"rmin"); zplaneRmax = xmlGetProp(cur,"rmax"); printf("Rmin=%s ----- Rmax=%s\n",zplaneRmin,zplaneRmax); } if(!xmlStrcmp(cur->name,(const xmlChar *)"layer")) { layerId = xmlGetProp(cur,"id"); layerInner_r = xmlGetProp(cur,"inner_r"); layerOuter_z = xmlGetProp(cur,"outer_z"); printf("layer id=%s ----- inner_r=%s ------ outer_z=%s\n",layerId,layerInner_r,layerOuter_z); } cur = cur->next; } return; }