#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
//Load in the xml file from disk
xmlDocPtr pDoc = xmlParseFile("file.xml");
//Or from a string xmlDocPtr pDoc = xmlNewDoc("<root><element/></root>");
//Do something with the document
//....
//Save the document back out to disk.
xmlSaveFileEnc("file.xml", pDoc, "UTF-8");
您想要的主要内容可能是这些功能:
xmlNodePtr pNode = xmlNewNode(0, (xmlChar*)"newNodeName");
xmlNodeSetContent(pNode, (xmlChar*)"content");
xmlAddChild(pParentNode, pNode);
xmlDocSetRootElement(pDoc, pParentNode);
这是一个使用 xpath 选择事物的快速示例:
//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);