#include<libxml/parser.h>
#include<libxml/tree.h>
void writeXML(char* fileName)
{
xmlDocPtr doc;
xmlNodePtr rootNode;
xmlNodePtr basicNode;
xmlNodePtr nodeContents;
xmlNodePtr sonNode;
xmlNodePtr grandsonNode;
//create document
doc = xmlNewDoc(BAD_CAST XML_DEFAULT_VERSION);
rootNode = xmlNewNode(NULL,BAD_CAST "rootNode");
//set root node
xmlDocSetRootElement(doc,rootNode);
//add nodes
xmlNewTextChild(rootNode, NULL, BAD_CAST "nodes", BAD_CAST "nodes1");
xmlNewTextChild(rootNode, NULL, BAD_CAST "nodes", BAD_CAST "nodes2");
xmlNewTextChild(rootNode, NULL, BAD_CAST "nodes", BAD_CAST "nodes3");
//add a basic node which has attribute and contents
basicNode = xmlNewNode(NULL,BAD_CAST "basicNode");
nodeContents = xmlNewText(BAD_CAST "contents");
xmlNewProp(basicNode,BAD_CAST "size",BAD_CAST "123");//add a attribute
xmlAddChild(basicNode,nodeContents);//add contents to node
xmlAddChild(rootNode,basicNode);//add node to root
//nesting
sonNode = xmlNewNode(NULL,BAD_CAST "son");
grandsonNode = xmlNewNode(NULL,BAD_CAST "grandson");
xmlAddChild(grandsonNode,xmlNewText(BAD_CAST "nesting node"));
xmlAddChild(sonNode,grandsonNode);
xmlAddChild(rootNode,sonNode);
//save file
int save = xmlSaveFile(fileName,doc);
if(save!=-1){
printf("write %d bytes\n",save);
}
//free memory
xmlFreeDoc(doc);
xmlCleanupParser();
}
void readXML(char* fileName)
{
xmlDocPtr doc;
xmlNodePtr node;
xmlChar *key;
doc = xmlReadFile(fileName,"UTF-8",XML_PARSE_RECOVER);
if(doc == NULL){
return;
}
node = xmlDocGetRootElement(doc);
if(node == NULL){
return;
}
if(!xmlStrcmp(node->name,BAD_CAST "root")){
xmlFreeDoc(doc);
return;
}
node = node->xmlChildrenNode;
xmlNodePtr attrNode = node;
printf("start reading...\n");
while(node!=NULL){
if(!xmlStrcmp(node->name,(const xmlChar*)"basicNode")){
key = xmlNodeGetContent(node);//get the contents of the node
printf("basicNode:%s\n",key);
xmlFree(key);
}
if(xmlHasProp(node,BAD_CAST "size")){
attrNode = node;//save node which has attribute-"size"
}
node = node->next;
}
// get attribute
xmlAttrPtr attrPtr = attrNode->properties;
while(attrPtr!=NULL){
if (!xmlStrcmp(attrPtr->name, BAD_CAST "size")){
xmlChar* attr = xmlGetProp(attrNode,BAD_CAST "size");
printf("sizeAttr=%s\n",attr);
xmlFree(attr);
}
attrPtr = attrPtr->next;
}
xmlFree(doc);
}
int main(){
char *fileName = "Demo.xml";
writeXML(fileName);
readXML(fileName);
}
write 193 bytes
start reading...
basicNode:contents
sizeAttr=123
libxml2读写
原创xiangjie256 博主文章分类:c++ ©著作权
文章标签 xml #include XML 文章分类 JavaScript 前端开发
上一篇:MVC
-
ProxySQL--读写分离(3)
ProxySQL--读写分离
MySQL proxysql -
libxml2 Push Parsing
http:/ all of it here, so you know where to go for the
xml sed cocoa iphone perl