parsing the value in between two XML tags

被刻印的时光 ゝ 提交于 2020-01-11 12:45:47

问题


I know this one has been asked before, however I can't seem to find a suitable solution, so I 'll state the problem:

I have a string of characters that is similar to an XML file. It's not an XML string, but it has opening and closing tags. All the information resides in one single line, for example:

<user>username</username>random data;some more random data<another tag>data</anothertag>randomdata;<mydata>myinfo</mydata>some more random data....

etc...

I am trying to read ONLY what's in between <mydata></mydata>. Any way to just parse this?

thanks, code is appreciated.


回答1:


I would just use strstr():

char * get_value(const char *input)
{
  const char *start, *end;

  if((start = strstr(input, "<mydata>")) != NULL)
  {
    start += strlen("<mydata>");
    if((end = strstr(start, "</mydata>")) != NULL)
    {
      char *out = malloc(end - start + 1);
      if(out != NULL)
      {
        memcpy(out, start, (end - start));
        out[end - start] = '\0';
        return out;
      }
    }
  }
  return NULL;
}

Note that the above is untested, written directly into the SO edit box. So, it's almost guaranteed to contain at least one off-by-one error.



来源:https://stackoverflow.com/questions/3493714/parsing-the-value-in-between-two-xml-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!