일부 html 파일에서 약간을 파낼 필요가 있습니다. 먼저 해당 파일을 라인에서 하나의 태그로 읽을 수있는 형태로 변환하고 싶습니다. 그럼에도 html에 대한 경험이 없습니다. 누군가가 내 코드를 분쇄하고 잊어 버린 규칙을 지적 할 수 있습니까?html 트리를 만드는 방법은 무엇입니까?
실생활 페이지에서 내 코드가 작동하지 않습니다. 프로그램 실행이 끝나면 중첩 카운터는 0으로 설정되어야합니다. 프로그램은 만난 모든 중첩 태그를 그대로 두어야합니다. 그렇지 않습니다. 페이스 북 페이지의 경우 2000 개가 넘는 태그가 열려 있습니다.
도서관을 사용하라고 나에게 제안하기 전에는 아무 것도 볼 수 없었습니다. 내 페이지에 XML로 변환하는 것은 어떻게 든 실패하고 htmlcxx 라이브러리에는 적절한 문서가 없습니다.
#include <cstdio>
char get_char(FILE *stream) {
char c;
do
c = getc(stream);
while (c == ' ' || c == '\n' || c == '\t' || c == '\r');
return c;
}
void fun(FILE *stream, FILE *out) {
int counter = -1;
char c;
do {
c = get_char(stream);
if (c == EOF)
break;
if (c != '<') { // print text
for (int i = counter + 1; i; --i)
putc(' ', out);
fprintf(out, "TEXT: ");
do {
if (c == '\n')
fprintf(out, "<BR>"); // random separator
else
putc(c, out);
c = getc(stream);
} while (c != '<');
putc('\n', out);
}
c = getc(stream);
if (c != '/') { // nest deeper
++counter;
for (int i = counter; i; --i)
putc(' ', out);
} else { // go back in nesting
--counter;
// maybe here should be some exception handling
do // assuming there's no strings in quotation marks here
c = getc(stream);
while (c != '>');
continue;
}
ungetc(c, stream);
do { // reading tag
c = getc(stream);
if(c == '/') { // checking if it's not a <blahblah/>
c = getc(stream);
if (c == '>') {
--counter;
break;
}
putc('/', out);
putc(c, out);
} else if (c == '"') { // not parsing strings put in quotation marks
do {
putc(c, out); c = getc(stream);
if (c == '\\') {
putc(c, out); c = getc(stream);
if (c == '"') {
putc(c, out); c = getc(stream);
}
}
} while (c != '"');
putc(c, out);
} else if (c == '>') { // end of tag
break;
} else // standard procedure
putc(c, out);
} while (true);
putc('\n', out);
} while (true);
fprintf(out, "Counter: %d", counter);
}
int main() {
const char *name = "rfb.html";
const char *oname = "out.txt";
FILE *file = fopen(name, "r");
FILE *out = fopen(oname, "w");
fun(file, out);
return 0;
}