2010-08-31 140 views
1

我正在使用libxml2來解析HTML。 HTML可能如下所示:libxml2 - 在父節點的內容之前插入子節點

<div> 
    Some very very long text here. 
</div> 

我想插入一個子節點,例如,一個標題,在文本之前,像這樣:

<div> 
    <h3> 
     Some header here 
    </h3> 
    Some very very long text here. 
</div> 

不幸的是,libxml2的總是添加我的頭後的文字,像這樣:

<div> 
    Some very very long text here. 
    <h3> 
     Some header here 
    </h3> 
</div> 

我怎樣才能解決這個問題?

回答

2

文本內容是一個子節點,所以你可以得到一個指向文本節點的指針並使用xmlAddPrevSibling函數添加元素。這裏是一個例子,但沒有錯誤處理或適當的清理。

xmlInitParser(); 

// Create an XML document 
std::string content("<html><head/><body><div>Some long text here</div></body></html>"); 
xmlDocPtr doc = xmlReadMemory(content.c_str(), content.size(), "noname.xml", 0, 0); 

// Query the XML document with XPATH, we could use the XPATH text() function 
// to get the text node directly but for the sake of the example we'll get the 
// parent 'div' node and iterate its child nodes instead. 
std::string xpathExpr("/html/body/div"); 
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); 
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(BAD_CAST xpathExpr.c_str(), xpathCtx); 

// Get the div node 
xmlNodeSetPtr nodes = xpathObj->nodesetval; 
xmlNodePtr divNode = nodes->nodeTab[ 0 ]; 

// Iterate the div child nodes, though in this example we know 
// there'll only be one node, the text node. 
xmlNodePtr divChildNode = divNode->xmlChildrenNode; 
while(divChildNode != 0) 
    { 
    if(xmlNodeIsText(divChildNode)) 
     { 
     // Create a new element with text node 
     xmlNodePtr headingNode = xmlNewNode(0, BAD_CAST "h3"); 
     xmlNodePtr headingChildNode = xmlNewText(BAD_CAST "Some heading here"); 
     xmlAddChild(headingNode, headingChildNode); 

     // Add the new element to the existing tree before the text content 
     xmlAddPrevSibling(divChildNode, headingNode); 
     break; 
     } 
    divChildNode = divChildNode->next; 
    } 

// Display the result 
xmlDocDump(stdout, doc); 

xmlCleanupParser(); 
相關問題