goe
goe

Reputation: 5425

How to parse a value from an XML tag in C language?

I'm getting this string as an input "<operator value=1/>". How in C can I parse out this string to get the "1" back?

Upvotes: 0

Views: 1763

Answers (2)

Andrew Keith
Andrew Keith

Reputation: 7563

i am assuming your parsing the string without using any library and the string may not be legal. I once encountered this problem when parsing sgml.

there are a few ways to do this. You could use strstok to split the string to find the value 1, then convert it using atoi.

I would recommend you use a regex library to extract the string. It would handle more boundary cases.

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400454

If you know that that's exactly the type of string you'll always get, you can just use sscanf():

int value;
if(sscanf(theString, "<operator value=%d/>", &value) == 1)
    ;  // parsing succeeded, use value
else
    ;  // parsing failed

If you're going to be receiving more complex input, I recommend using an XML parsing library such as expat or TinyXML (requires C++).

Upvotes: 2

Related Questions