Skip to content

Commit

Permalink
Added encoding for toString() method (libxmljs#482)
Browse files Browse the repository at this point in the history
* Failing test case for stripped out entities

* Allow encoding to be specified for toString()
  • Loading branch information
rhodgkins authored Apr 29, 2022
1 parent 1768388 commit 6cd3e04
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/xml_document.cc
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ NAN_METHOD(XmlDocument::ToString)
assert(document);

int options = 0;
const char *encoding = "UTF-8";

if (info.Length() > 0) {
if (info[0]->IsBoolean()) {
Expand All @@ -186,6 +187,13 @@ NAN_METHOD(XmlDocument::ToString)
} else if (info[0]->IsObject()) {
v8::Local<v8::Object> obj = Nan::To<v8::Object>(info[0]).ToLocalChecked();

// choose encoding declaration
v8::Local<v8::Value> encodingOpt = Nan::Get(obj, Nan::New<v8::String>("encoding").ToLocalChecked()).ToLocalChecked();
if (encodingOpt->IsString()) {
std::string encoding_ = *Nan::Utf8String(encodingOpt);
encoding = encoding_.c_str();
}

// drop the xml declaration
if (Nan::Get(obj, Nan::New<v8::String>("declaration").ToLocalChecked()).ToLocalChecked()->IsFalse()) {
options |= XML_SAVE_NO_DECL;
Expand Down Expand Up @@ -227,7 +235,7 @@ NAN_METHOD(XmlDocument::ToString)
}

xmlBuffer* buf = xmlBufferCreate();
xmlSaveCtxt* savectx = xmlSaveToBuffer(buf, "UTF-8", options);
xmlSaveCtxt* savectx = xmlSaveToBuffer(buf, encoding, options);
xmlSaveTree(savectx, (xmlNode*)document->xml_obj);
xmlSaveFlush(savectx);
xmlSaveClose(savectx);
Expand Down
8 changes: 8 additions & 0 deletions test/html_parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,5 +151,13 @@ module.exports.toString = function(assert) {
assert.ok(doc.toString({ type: 'xml' }).indexOf('<?xml') > -1);
assert.ok(doc.toString({ type: 'xhtml' }).indexOf('<?xml') > -1);
assert.ok(doc.toString({ type: 'xml', selfCloseEmpty:true }).indexOf('<a/>') > -1);

doc = libxml.parseHtml("<a>Something&nbsp;with a space</a>");
assert.ok(doc.toString().indexOf('<?xml') === -1);
assert.ok(doc.toString({ type: 'xml' }).indexOf('<?xml') > -1);
assert.ok(doc.toString({ type: 'xhtml' }).indexOf('<?xml') > -1);
assert.ok(doc.toString({ type: 'xhtml' }).indexOf('&nbsp;') === -1);
assert.ok(doc.toString({ type: 'xhtml', encoding: 'HTML' }).indexOf('&nbsp;') > -1);
assert.ok(doc.toString({ type: 'xhtml', encoding: 'ASCII' }).indexOf('&#160;') > -1);
assert.done();
}

0 comments on commit 6cd3e04

Please sign in to comment.