#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("https://stackoverflow.com/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);
除了布萊恩·邦迪的偉大答覆,我已經寫了一篇關於libxml2的「如何開始」的小文章:http://charette.no-ip.com:81/programming/2010-01-03_LibXml2/ – 2010-01-13 00:30:37