How to add a xml node constructed from string in libxml2

后端 未结 4 599
栀梦
栀梦 2021-02-09 13:34

I am using Libxml2 for encoding the data in a xml file. My data contain tags like \"<\" and \">\". when it is converted into xml these tags are also converted into \"<\

4条回答
  •  不知归路
    2021-02-09 14:10

    If you want a string to be treated as xml, then you should parse it and obtain xmlDoc from it, using xmlReadMemory. It could be usable for larger strings, but usually the document is builded using single step instructions, like in Joachim's answer. Here I present xmlAddChildFromString function to do the stuff in a string way.

    #include 
    #include 
    #include 
    #include 
    
    /// Returns 0 on failure, 1 otherwise
    int xmlAddChildFromString(xmlNodePtr parent, xmlChar *newNodeStr)
    {
      int rv = 0;
      xmlChar *newNodeStrWrapped = calloc(strlen(newNodeStr) + 10, 1);
      if (!newNodeStrWrapped) return 0;
      strcat(newNodeStrWrapped, "");
      strcat(newNodeStrWrapped, newNodeStr);
      strcat(newNodeStrWrapped, "");
      xmlDocPtr newDoc = xmlReadMemory(
        newNodeStrWrapped, strlen(newNodeStrWrapped),
        NULL, NULL, 0);
      free(newNodeStrWrapped);
      if (!newDoc) return 0;
      xmlNodePtr newNode = xmlDocCopyNode(
        xmlDocGetRootElement(newDoc),
        parent->doc,
        1);
      xmlFreeDoc(newDoc);
      if (!newNode) return 0;
      xmlNodePtr addedNode = xmlAddChildList(parent, newNode->children);
      if (!addedNode) {
        xmlFreeNode(newNode);
        return 0;
      }
      newNode->children = NULL; // Thanks to milaniez
      newNode->last = NULL;     // for fixing
      xmlFreeNode(newNode);     // the memory leak.
      return 1;
    }
    
    int
    main(int argc, char **argv)
    {
        xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
        xmlNodePtr root = xmlNewNode(NULL, BAD_CAST "root");
        xmlDocSetRootElement(doc, root);
        xmlAddChildFromString(root,
          "Park Streetkolkata");
        xmlDocDump(stdout, doc);
        xmlFreeDoc(doc);
        return(0);
    }
    

提交回复
热议问题