libxml2读写


#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值