2012-07-09 80 views
0

我只想讀取之前寫出文件的XML節點內容中的字符串。下面是代碼:無法使用libxml2讀取XML節點的內容

int main() { 

xmlNodePtr n, n2, n3; 
xmlDocPtr doc; 
xmlChar *xmlbuff; 
int buffersize; 
xmlChar* key; 

doc = xmlNewDoc(BAD_CAST "1.0"); 
n = xmlNewNode(NULL, BAD_CAST "root"); 


xmlNodeSetContent(n, BAD_CAST "test1"); 
n2 = xmlNewNode(NULL, BAD_CAST "devices"); 
xmlNodeSetContent(n2, BAD_CAST "test2"); 
n3 = xmlNewNode(NULL, BAD_CAST "device"); 
xmlNodeSetContent(n3, BAD_CAST "test3"); 

//n2 = xmlDocCopyNode(n2, doc, 1); 
xmlAddChild(n2,n3); 
xmlAddChild(n,n2); 


xmlDocSetRootElement(doc, n); 


xmlSaveFormatFileEnc(FILENAME, doc, "utf-8", 1); 

doc = xmlParseFile(FILENAME); 
n = xmlDocGetRootElement(doc); 

key = xmlNodeListGetString(doc, n, 1); 
printf("keyword: %s\n", key); 
xmlFree(key); 

n = n->children; 

key = xmlNodeListGetString(doc, n, 1); 
printf("keyword: %s\n", key); 
xmlFree(key); 

n = n->children; 

key = xmlNodeListGetString(doc, n, 1); 
printf("keyword: %s\n", key); 
xmlFree(key); 

n2 = xmlNewNode(NULL, BAD_CAST "address"); 
xmlAddChild(n,n2); 

xmlDocSetRootElement(doc, n); 

xmlSaveFormatFileEnc(FILENAME, doc, "utf-8", 1); 

return 0; 
} 

這段代碼的輸出是 - > 關鍵字:(空) 關鍵字:TEST1 關鍵字:(空)

我爲什麼不能閱讀TEST2 TEST3和?

在此先感謝。

回答

1

您正在生成的XML文件是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<root> 
    test1 
    <devices> 
     test2 
     <device> 
      test3 
     </device> 
    </devices> 
</root> 

在libxml的,孩子們既包含文本節點和元素。您需要檢查類型字段以瞭解節點指向的內容。這裏是你可以使用的代碼(我確定有更好的方法來做到這一點,但它清楚地顯示你應該執行的類型測試)。我使用n代表元素節點,n2代表文本節點搜索。

// Get <root>  
n = xmlDocGetRootElement(doc); 
n2 = n -> children; 
while (n2 != NULL && n2 -> type != XML_TEXT_NODE) 
    n2 = n2 -> next; 
if (n2 != NULL) 
{ 
    key = xmlNodeListGetString(doc, n2, 1); 
    printf("keyword: %s\n", key); 
    xmlFree(key); 
} 

// grab child 
n = n -> children; 
while (n != NULL && n -> type != XML_ELEMENT_NODE) 
    n = n -> next; 
if (n == NULL) 
    return -1; 

// grab its 1st text child  
n2 = n -> children; 
while (n2 != NULL && n2 -> type != XML_TEXT_NODE) 
    n2 = n2 -> next; 
if (n2 != NULL) 
{ 
    key = xmlNodeListGetString(doc, n2, 1); 
    printf("keyword: %s\n", key); 
    xmlFree(key); 
} 

// grab child 
n = n -> children; 
while (n != NULL && n -> type != XML_ELEMENT_NODE) 
    n = n -> next; 
if (n == NULL) 
    return -1; 

// grab its 1st text child  
n2 = n -> children; 
while (n2 != NULL && n2 -> type != XML_TEXT_NODE) 
    n2 = n2 -> next; 
if (n2 != NULL) 
{ 
    key = xmlNodeListGetString(doc, n2, 1); 
    printf("keyword: %s\n", key); 
    xmlFree(key); 
}