linux下libxml2应用--生成一个tree并且保存为xml文件

来源:互联网 发布:go语言网络编程 编辑:程序博客网 时间:2024/04/30 02:57
导读:
  #include
  #include
  #include
  #define BUF 200
  // 该函数生成tree并且将tree的内容保存为xml格式以及将tree的内容转换成字符串带出来
  int MakeXmldata(char* cxmlbuff)
  {
  xmlDocPtr doc = NULL; // document pointer
  xmlNodePtr root_node = NULL, node1 = NULL, node2 = NULL; // node pointers
  // Creates a new document, a node and set it as a root node
  doc = xmlNewDoc(BAD_CAST"1.0");
  root_node = xmlNewNode(NULL, BAD_CAST"root");
  xmlDocSetRootElement(doc, root_node);
  // creates a new node, which is "attached" as child node of root_node node.
  node1 = xmlNewChild(root_node, NULL, BAD_CAST"node1", BAD_CAST"node-1");
  // xmlNewProp() creates attributes, which is "attached" to an node.
  node2 = xmlNewChild(root_node, NULL, BAD_CAST"node2", BAD_CAST"node-2");
  // 给节点添加属性说明
  xmlNewProp(node2, BAD_CAST"attribute", BAD_CAST"yes");
  // 用另一种方法生成节点
  node2 = xmlNewText(BAD_CAST"node-3");
  xmlAddChild(node1, node2);
  // Dumping document to stdio or file
  xmlAddChild(root_node, node1);
  // 将生成的tree保存为xml格式的文件
  xmlSaveFormatFileEnc("xmltest.xml", doc, "UTF-8", 1);
  // 将tree的内容转化为字符串
原创粉丝点击