2012-01-30 67 views
1

我需要將一小段代碼從PHP移植到C,該代碼片段提取各種元素的值,這些元素可以按照其樹中的級別的任意順序排列。一個例子的XML文檔是:使用xmllib2 for C獲取元素值

<book> 
    <author>John Smith</author> 
    <title>A Marvelous Book</title> 
</book> 

在PHP的代碼,以提取標題是:

$xmlDoc = new SimpleXMLElement($xmlStr); 
$title = $xmlDoc->title; 

對於我將使用的libxml2(其中我沒有熟悉)C。到目前爲止,我有:

xmlDoc = xmlReadMemory(xmlStr, strlen(xmlStr), "noname.xml", NULL, 0); 

現在是什麼?我應該使用XPATH來提取標題嗎?似乎過度殺傷... 請指教。

回答

1

所以我落得這樣做,例如提取標題,就是:

if (xpathCtx = xmlXPathNewContext(doc)) { 
    if (xpathObj = xmlXPathEvalExpression("//title[1]", xpathCtx)) { 
     if (nodes = xpathObj->nodesetval) { 
      if ((nodes->nodeNr == 1) && (nodes->nodeTab[0]->type == XML_ELEMENT_NODE)) { 
       value = xmlNodeGetContent(xpathObj->nodesetval->nodeTab[0]); 
      } 
     } 
    } 
} 

呸!