Search code examples
cxmllibxml2

XML : Get an array of string from text cut by element


I need to get an array of string from a text in a node which is itself cut by an other element in a xml file. I work in C with the libxml2 library.

Exemple :
<option>some text <middletag />other text</option>

I tried with xmlNodeGetContent(xmlnode); but I only get a string like "some text other text".

The question is : Is it possible to get an array of string which, with this exemple, would be {"some text ", "other text"}?


Solution

  • I have found the solution, and I have to say I feel ashamed because it took me too much time to find it.

    It's simple, I take this exemple again :

    <option>some text <middletag />other text</option>
    

    With this you can have a xmlnode * on the <option> node. We can find the part some text <middletag />other text with a loop on the list xmlnode->children. We just have to look for the nodes with the type XML_TEXT_NODE and get the content.

    Code :

    xmlNode *node = option_node->children;
    for (; node; node = node->next){
        if (node->type == XML_TEXT_NODE) {
            printf("%s\n", node->content);
        }
    }
    

    Result :

    some text
    other text
    

    Now, with malloc / realloc, we can save it in an array.