[Expat-discuss] how XML_Parse work with processing instruction?

Chen Ming chenming442 at gmail.com
Fri Sep 8 13:42:44 CEST 2006


Hi everyone, I try the following code both in VC7 and Dev-CPP.
But XML_Parse function seems can't work properly with processing
instruction like <?xml version="1.0" ?>

In the following code,the first time XML_Parse is called for string
"<?xml", it return XML_STATUS_OK; but the seconde time for string
"version="1.0"", it return XML_STATUS_ERROR,and error string form
XML_ErrorString is "not well-formed (invalid token)". If I remove the
processing instruction, everything is ok.

I guess maybe the usage of file stream has problem, but can't get it clear
, can somebody explain this error?
=============================================================
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <expat.h>

using namespace std;

int Count;
const int BUFFERSIZE = 256;

void XMLCALL start(void *data, const char *el, const char **attr)
{
  const char* tag = "tag1";
  if (strcmp(el, tag) == 0)
  Count++;
}  /* End of start handler */

void XMLCALL end(void *data, const char *el)
{
  const char* end = "tag";
}  /* End of end handler */


int main(int argc, char *argv[])
{
    getchar();
    XML_Parser p = XML_ParserCreate(NULL);
    if (p == NULL)
    {
      cout << "Parser create failed!" <<endl;
      system("PAUSE");
      return EXIT_FAILURE;
    }

    XML_SetElementHandler(p, start, end);

    Count = 0;
    char buffer[BUFFERSIZE];
    int done = 0;

    ifstream file("test.xml", ios::in);
    if (!file)
    {
      cout << "File could not be opend!" <<endl;
      system("PAUSE");
      return EXIT_FAILURE;
    }

    while (file >> buffer)
    {
      int length = strlen(buffer);
      done = file.eof();
      XML_Status status = XML_Parse(p, buffer, length, done);
      if (status == XML_STATUS_ERROR)
      {

        string error = XML_ErrorString(XML_GetErrorCode(p));
        cout << "parse error: " << error << endl;
        system("PAUSE");
        return EXIT_SUCCESS;
      }

      if (done)
      break;
    }
    cout << "There are " << Count << " <tag>." << endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}


More information about the Expat-discuss mailing list