问题
When I print out information from my XML document I get �� before each line. Here is my XML document.
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Here is my code
#include <cstdio>
#include <expat.h>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
void XMLCALL start(void*,const char*, const char**);
void XMLCALL end(void*,const char*);
void XMLCALL character(void*, const char*, int);
int main()
{
int size;
fstream fin("note.xml", ios::in | ios::binary | ios::ate);
size = fin.tellg();
char* data = new char [size + 1];
fin.seekg(0, ios::beg);
XML_Parser parser = XML_ParserCreate("ISO-8859-1");
XML_SetElementHandler(parser, start, end);
XML_SetCharacterDataHandler(parser, character);
fin.read(data, size);
XML_Parse(parser, data, size , fin.eof());
XML_ParserFree(parser);
fin.close();
delete [] data;
}
void XMLCALL start(void* data, const char* name, const char** atts)
{
if((strcmp(name, "note")) == 0)
{
printf("-- Note --<br> ");
}
else if((strcmp(name,"to")) == 0)
{
printf("To: ");
}
else if((strcmp(name,"from")) == 0)
{
printf("From: ");
}
else if((strcmp(name,"heading")) == 0)
{
printf("Heading: ");
}
else if((strcmp(name, "body")) == 0)
{
printf("Message: ");
}
}
void XMLCALL end(void* data,const char* name)
{
printf("<br>");
}
void XMLCALL character(void* data, const char* info, int length)
{
printf("%s",info);
}
This is what it prints out:
-- Note --<br>
�To: Tove<br>
xFrom: Jani<br>
xHeading: Reminder<br>
xMessage: Don't forget me this weekend!<br>
x<br>
This is what I want it to print out:
-- Note --<br>
To: Tove<br>
From: Jani<br>
Heading: Reminder<br>
Message: Don't forget me this weekend!<br>
<br>
Any assistance will be greatly appreciated. Thank You
回答1:
Character is called for the '\n' on the end of the line with length = 1. The other characters are junk after the '\n' in the info string.
来源:https://stackoverflow.com/questions/15053583/expat-prints-out-garbage-when-i-print-to-screen-or-file