I am new to libxml. I would like to write 1 loop to loop through all the children of a child node etc. e.g.
<par>i want to <bold>loop <ital开发者_运维问答ic>through </italic> all</bold> children in this node</pa
r>
At the moment my looping code look as follows but I only get the "bold" node and not the "italic" child.
if (xmlStrEqual(node->name, BAD_CAST "p")) {
xmlNodePtr child = node->children;
while (child != NULL) {
child = child->next;
}
}
It is conceivable that the node structure could grow to 4-5 elements, so I need a solution which is more robust that putting while loops within while loops. Any help would be appreciated please.
The xmlTree interface you're using is heirarchical. <par> has 3 children - the text before <bold>, <bold> itself, and the text after. <bold> has children of its own, which includes <italic>. The node->children list only contains the immediate children of a node.
There are a couple ways to get the behavior that you want.
While processing child, you can recursively process child->children to get to <bold>'s child, which includes <italics>
If you're looking SPECIFICALLY for that <itallic> (or for a set of specific nodes), you can use an XPath expression, such as "par//italic" to find any italic node anywhere beneath par. http://www.xmlsoft.org/examples/index.html#XPath
You could look at libxml2's xmlTextReader interface rather than this xmlTree. It provides the serial "read through" of the document that you're expecting. http://xmlsoft.org/xmlreader.html
Each method has its own advantages/disadvantages, depending on what all you're trying to do with your application.
精彩评论