#include <stdio.h>
#include <libxml/parser.h>
int main(int argc, char* argv[])
{
xmlDocPtr doc; //定義解析文檔指針
xmlNodePtr curNode; //定義結點指針(你需要它為了在各個結點間移動)
xmlChar *szKey; //臨時字符串變量
char *szDocName;
if (argc <= 1) {
printf("Usage: %s docname\n", argv[0]);
return -1;
}
szDocName = argv[1];
doc = xmlReadFile(szDocName, "GB2312", XML_PARSE_RECOVER); //以GB2312的編碼方式讀入解析文件
//檢查解析文檔是否成功,如果不成功,libxml將指一個注冊的錯誤並停止。
//一個常見錯誤是不適當的編碼。XML標准文檔除了用UTF-8或UTF-16外還可用其它編碼保存。
//如果文檔是這樣,libxml將自動地為你轉換到UTF-8。更多關於XML編碼信息包含在XML標准中.
if (NULL == doc) {
fprintf(stderr,"Document is not parsed successfully. \n");
return -1;
}
curNode = xmlDocGetRootElement(doc); //確定文檔根元素
/*檢查確認當前文檔中包含內容*/
if (NULL == curNode) {
fprintf(stderr,"the document is empty.\n");
xmlFreeDoc(doc);
return -1;
}
/*在這個例子中,我們需要確認文檔是正確的類型。“root”是在這個示例中使用文檔的根類型。*/
if (xmlStrcmp(curNode->name, BAD_CAST "root")) {
fprintf(stderr,"document of the wrong type, root_node is not root");
xmlFreeDoc(doc);
return -1;
}
curNode = curNode->xmlChildrenNode;
xmlNodePtr propNodePtr = curNode;
while(NULL != curNode) {
//取出節點中的內容
if ((!xmlStrcmp(curNode->name, (const xmlChar *)"newNode1"))) {
szKey = xmlNodeGetContent(curNode);
printf("newNode1: %s\n", szKey);
xmlFree(szKey);
}
//查找帶有屬性attribute的節點
if (xmlHasProp(curNode, BAD_CAST "attribute")) {
propNodePtr = curNode;
}
curNode = curNode->next;
}
//查找屬性
xmlAttrPtr attrPtr = propNodePtr->properties;
while (attrPtr != NULL) {
if (!xmlStrcmp(attrPtr->name, BAD_CAST "attribute")) {
xmlChar* szAttr = xmlGetProp(propNodePtr, BAD_CAST "attribute");
printf("get attribute = %s\n", szAttr);
xmlFree(szAttr);
}
attrPtr = attrPtr->next;
}
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
