毕业设计需要用到xml文件来组织和存放数据,
对于Linux环境下,有libxml2可供使用。
经过一段时间查询文档和网站,
基本掌握创建xml文档和解析xml的操作,
简单做一下记录。
创建xml
例子如下:
1 #include <stdio.h> 2 #include <libxml/parser.h> 3 #include <libxml/tree.h> 4 5 int main(int argc, char **argv) 6 { 7 xmlDocPtr doc = NULL; 8 xmlNodePtr root_node = NULL, node = NULL, node1 = NULL; 9 10 doc = xmlNewDoc(BAD_CAST "1.0"); // create a new xml document. 11 root_node = xmlNewNode(NULL, BAD_CAST "root"); // create a root node. 12 xmlDocSetRootElement(doc, root_node); 13 14 xmlNewChild(root_node, NULL, BAD_CAST "node1", BAD_CAST "content of node1"); 15 //xmlNewChild(root_node, NULL, BAD_CAST "node2", NULL); 16 17 node = xmlNewChild(root_node, NULL, BAD_CAST "node3", BAD_CAST "node3 has attributes"); 18 xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "yes"); 19 20 node = xmlNewNode(NULL, BAD_CAST "node4"); 21 node1 = xmlNewText(BAD_CAST 22 "other way to create content (which is also a node)"); 23 xmlAddChild(node, node1); 24 xmlAddChild(root_node, node); 25 26 xmlSaveFormatFileEnc(argc > 1 ? argv[1] : "-", doc, "UTF-8", 1); 27 28 xmlFreeDoc(doc); 29 30 xmlCleanupParser(); 31 32 xmlMemoryDump(); 33 return(0); 34 }