how to use libxml2 to modify an existing xml file?

前端 未结 1 1938
Happy的楠姐
Happy的楠姐 2021-02-02 02:00

I need to take an existing xml file, and modify just a few attributes and write the file back out.

I was thinking of using libxml2 to get this done. Application is C/C+

1条回答
  •  无人共我
    2021-02-02 02:48

    #include 
    #include 
    #include 
    
    //Load in the xml file from disk
    xmlDocPtr pDoc = xmlParseFile("file.xml");
    //Or from a string xmlDocPtr pDoc = xmlNewDoc("");
    
    //Do something with the document
    //....
    
    //Save the document back out to disk.
    xmlSaveFileEnc("file.xml", pDoc, "UTF-8");
    

    The main things you want are probably these functions:

    xmlNodePtr pNode = xmlNewNode(0, (xmlChar*)"newNodeName");
    xmlNodeSetContent(pNode, (xmlChar*)"content");
    xmlAddChild(pParentNode, pNode);
    xmlDocSetRootElement(pDoc, pParentNode);
    

    And here is a quick example of using xpath to select things:

    //Select all the user nodes
    xmlChar *pExpression((xmlChar*)_T("/users/user"));
    xmlXPathObjectPtr pResultingXPathObject(getnodeset(pDoc, pExpression));
    if (pResultingXPathObject)
    {
        xmlNodeSetPtr pNodeSet(pResultingXPathObject->nodesetval);
        for(int i = 0; i < pNodeSet->nodeNr; ++i) 
        {
            xmlNodePtr pUserNode(pNodeSet->nodeTab[i]);
                       //do something with the node
        }
    }
    xmlXPathFreeObject(pResultingXPathObject);
    

    0 讨论(0)
提交回复
热议问题