0. LIBXML2 is a cross-platform C library for manipulating XML files. API Reference.
1. Structure:
1 /*Document Structure Body*/2typedef xmldoc *xmldocptr;3 4 /*node Structure Body*/5typedefstruct_xmlnode XmlNode;6typedef XmlNode *xmlnodeptr;7 struct_xmlnode {8 void*_private;/*Application Data*/9Xmlelementtype type;/*type number, must be second!*/Ten ConstXmlchar *name;/*the name of the node, or the entity*/ One struct_xmlnode *children;/*parent->childs Link*/ A struct_xmlnode *last;/*Last Child link*/ - struct_xmlnode *parent;/*child->parent Link*/ - struct_xmlnode *next;/*Next Sibling link*/ the struct_xmlnode *prev;/*previous Sibling Link*/ - struct_xmldoc *doc;/*The containing document*/ - - /*End of Common part*/ +XmlNs *ns;/*pointer to the associated namespace*/ -Xmlchar *content;/*The content*/ + struct_xmlattr *properties;/*Properties List*/ AXmlNs *nsdef;/*namespace definitions on this node*/ at void*PSVI;/*For TYPE/PSVI informations*/ -Unsigned ShortLine/* Line number*/ -Unsigned ShortExtra/*extra data for xpath/xslt*/ - }; - - Other APIs: inXmlchildelementcount/*gets the number of child nodes of a node*/ - /*transcoding API*/ to#include"iconv.h" + intIConvert (Const Char*from_code,Const Char*to_code,Const Char*from_str, size_t F_len,Char*to_str, size_t T_len) - { the iconv_t cd; * size_t ret; $cd =Iconv_open (To_code, from_code);Panax Notoginseng if(cd = = (iconv_t)-1 ) { -Perror ("Iconv Open error\n"); the return-1; + } ARET = Iconv (CD, &from_str, &f_len, &to_str, &T_len); the if(ret = = (size_t)-1 ) + { -Perror ("iconv error\n"); $ iconv_close (CD); $ return-1; - } - iconv_close (CD); the returnret; -}
2. READ:
1 Xmldocptr doc = xmlreadfile ("file.xml"0)2/ * or */ 3 Xmldocptr doc = xmlparsefile ("file.xml");
3. Traversal:
1 /*The order of preservation of the sibling nodes and the order of the files are not guaranteed to be consistent*/2 /*the internal byte encoding of the libxml is utf-8, so if the node content is GBK Chinese, it needs to be transcoded with Iconv .*/3 /*Root*/4Xmlnodeptr cur =Xmldocgetrootelement (DOC);5 /*Children & Sibling*/6Cur = cur->children;7 while(cur) {8 if(XMLSTRCMP (Cur->name, Bad_cast ("nodename")) ==0 ) {9 /*Read Property*/Ten Char* P_value = Xmlgetprop (cur, bad_cast ("Propername")); One /*Read Content*/ A Char* N_value =xmlnodegetcontent (cur); - /*convert encode if needed*/ -ret = IConvert ("Utf-8","GBK", N_value, Xmlstrlen (N_value), Outbuffer, Outlen); the ... - /*Free is needed*/ - Xmlfree (p_value); - Xmlfree (n_value); + } -Cur = cur->Next; + } AXmlfree (DOC);
4. Find:
1. If only one of the result items is found, the node can be found by self-traversal;
2. There are multiple nodes matching, can find the node set by xmlxpatheval*;
5. Modify and Save: Use later to add ...
Some uses of LIBXML2