资源描述:
《Libxml2使用实例》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、XML--Libxml2使用实例一,使用Libxml2生成xml1,编辑生成#include#include#includeintmain(intargc,char**argv){xmlDocPtrdoc=NULL;/*documentpointer*/xmlNodePtrroot_node=NULL,node=NULL,node1=NULL;/*nodepointers*///Createsanewdocument,anodeandsetitasarootnodedoc=xmlNewDoc(BA
2、D_CAST"1.0");root_node=xmlNewNode(NULL,BAD_CAST"root");xmlDocSetRootElement(doc,root_node);//createsanewnode,whichis"attached"aschildnodeofroot_nodenode.xmlNewChild(root_node,NULL,BAD_CAST"node1",BAD_CAST"contentofnode1");//xmlNewProp()createsattributes,whichis"attached"toannode.node=xmlNewC
3、hild(root_node,NULL,BAD_CAST"node3",BAD_CAST"nodehasattributes");xmlNewProp(node,BAD_CAST"attribute",BAD_CAST"yes");//Heregoesanotherwaytocreatenodes.node=xmlNewNode(NULL,BAD_CAST"node4");node1=xmlNewText(BAD_CAST"otherwaytocreatecontent");xmlAddChild(node,node1);xmlAddChild(root_node,node);
4、//DumpingdocumenttostdioorfilexmlSaveFormatFileEnc(argc>1?argv[1]:"-",doc,"UTF-8",1);/*freethedocument*/xmlFreeDoc(doc);xmlCleanupParser();xmlMemoryDump();//debugmemoryforregressiontestsreturn0;}2,编译运行gccmain.c-omain.out-I/usr/include/libxml2-lxml23,生成的xml
5、contentofnode1nodehasattributesotherwaytocreatecontent两个实例,说明如何使用Libxml2遍历xml文档和使Xpath获取特定结点的内容值:程序使用的xml文档如下:contentofnode1nodehasattribute
6、sotherwaytocreatecontent二,遍历程序代1,代码#include#include#includeintmain(intargc,char**argv){xmlDocPtrdoc=NULL;xmlNodePtrcur=NULL;char*name=NULL;char*value=NULL;xmlKeepBlanksDefault(0);if(argc<2){printf("ERROR:argcmustbe2orabov
7、e.");return-1;}//createDomtreedoc=xmlParseFile(argv[1]);if(doc==NULL){printf("ERROR:Loadingxmlfilefailed.");exit(1);}//getrootnodecur=xmlDocGetRootElement(doc);if(cur==NULL){printf("ERROR:emptyfile");xmlFreeDoc(doc);exit(2);}//walkthetreecur=