forked from libxmljs/libxmljs
/
html_parser.cc
87 lines (68 loc) · 2.47 KB
/
html_parser.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2009, Squish Tech, LLC.
#include "xml_syntax_error.h"
#include "html_parser.h"
#include "html_document.h"
namespace libxmljs {
inline v8::Handle<v8::Value>
BuildDoc(xmlDoc *doc, v8::Handle<v8::Array> errors) {
v8::HandleScope scope;
if (doc == NULL) {
xmlFree(doc);
xmlError *error = xmlGetLastError();
if (error) {
return v8::ThrowException(XmlSyntaxError::BuildSyntaxError(error));
} else {
return v8::ThrowException(v8::Exception::Error(
v8::String::New("Could not parse XML string")));
}
return v8::Null();
}
v8::Handle<v8::Object> jsDoc =
LibXmlObj::GetMaybeBuild<HtmlDocument, xmlDoc>(doc);
HtmlDocument *document = LibXmlObj::Unwrap<HtmlDocument>(jsDoc);
document->errors = v8::Persistent<v8::Array>::New(errors);
return scope.Close(jsDoc);
}
v8::Handle<v8::Value>
ParseHtmlString(const v8::Arguments& args) {
v8::HandleScope scope;
if (!args[0]->IsString())
return v8::ThrowException(v8::Exception::Error(
v8::String::New("Must supply parseHtmlString with a string")));
v8::Persistent<v8::Array> errors = v8::Persistent<v8::Array>::New(
v8::Array::New());
xmlResetLastError();
xmlSetStructuredErrorFunc(reinterpret_cast<void *>(*errors),
XmlSyntaxError::PushToArray);
v8::String::Utf8Value str(args[0]->ToString());
htmlDocPtr doc = htmlReadMemory(*str, str.length(), NULL, NULL, 0);
xmlSetStructuredErrorFunc(NULL, NULL);
return scope.Close(BuildDoc(doc, errors));
}
v8::Handle<v8::Value>
ParseHtmlFile(const v8::Arguments& args) {
v8::HandleScope scope;
if (!args[0]->IsString())
return v8::ThrowException(v8::Exception::Error(
v8::String::New("Must supply parseHtmlFile with a filename")));
v8::Persistent<v8::Array> errors = v8::Persistent<v8::Array>::New(
v8::Array::New());
xmlResetLastError();
xmlSetStructuredErrorFunc(reinterpret_cast<void *>(*errors),
XmlSyntaxError::PushToArray);
v8::String::Utf8Value str(args[0]->ToString());
htmlDocPtr doc = htmlReadFile(*str, NULL, 0);
xmlSetStructuredErrorFunc(NULL, NULL);
return scope.Close(BuildDoc(doc, errors));
}
void
HtmlParser::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope;
LIBXMLJS_SET_METHOD(target,
"parseHtmlString",
ParseHtmlString);
LIBXMLJS_SET_METHOD(target,
"parseHtmlFile",
ParseHtmlFile);
}
} // namespace libxmljs