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+
#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);