-1

I have a simple xml string defined in the following way in a c code:

char xmlstr[] = "<root><str1>Welcome</str1><str2>to</str2><str3>wonderland</str3></root>";

I want to parse the xmlstr to fetch all the values assigned to str1,str2,str3 tags.

I am using libxml2 library. As I am less experienced in xml handling, I unable get the values of the required tags. I tried some sources from net, but I am ending wrong outputs.

Constantinius
  • 34,183
  • 8
  • 77
  • 85

2 Answers2

1

Using the libxml2 library parsing your string would look something like this:

char xmlstr[] = ...;
char *str1, *str2, *str3;
xmlDocPtr doc = xmlReadDoc(BAD_CAST xmlstr, "http://someurl", NULL, 0);
xmlNodePtr root, child;

if(!doc)
{ /* error */ }

root = xmlDocGetRootElement(doc);

now that we have parsed a DOM structure out of your xml string, we can extract the values by iterating over all child values of your root tag:

for(child = root->children; child != NULL; child = child->next)
{
    if(xmlStrcmp(child->name, BAD_CAST "str1") == 0)
    {
        str1 = (char *)xmlNodeGetContent(child);
    }

    /* repeat for str2 and str3 */
    ...
}
Constantinius
  • 34,183
  • 8
  • 77
  • 85
  • what is the significance of url in the above. What I hve to give for my program – user976211 Oct 03 '11 at 10:10
  • To be frank I'm not sure. The docs only state that this is used as a "*base*", whatever that means. I guess it is not important in that small example. – Constantinius Oct 03 '11 at 10:15
  • I too found the same. However, thanks for your help. I could do that small patch code to embed into my huge application. – user976211 Oct 03 '11 at 10:29
0

I usual do xml parsing using minixml library

u hope this will help you

http://www.minixml.org/documentation.php/basics.html

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222