From a practical point of view, I would expect addChild to simply insert the TEXT node at the specified point in the tree rather than merge its content and then get freed. This last part is especially problematic for libxmljs as the example program below will crash with a SEGFAULT.
I'm starting to thing that perhaps a DOM API would be better suited for a scripting language, rather then staying true to libxml.
#!/usr/bin/env node
var http = require('http'),
events = require('events'),
inherits = require('sys').inherits,
libxml = require('libxmljs');
function WebClient(host, path) {
var self = this,
transport = http.createClient(80, host),
request = transport.request('GET', path, {'host': host});
request.end();
request.on('response', function (response) {
if (response.statusCode != 200) {
self.emit('done', response.statusCode, '');
}
else {
var text = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
text += chunk;
});
response.on('end', function (chunk) {
self.emit('done', 200, text);
});
}
});
}
inherits(WebClient, events.EventEmitter);
var client = new WebClient('
maps.google.com', '/maps/api/geocode/xml?address=salem&sensor=false');
client.on('done', function(status, xml) {
if (status != 200) {
throw 'unable to load URL';
}
// the XML looks something along the lines of
// <geometry>
// <location>
// <lat>44.9428975</lat>
// ...
// </location>
// </geometry>
// <geometry>
// <location>
// <lat>45.0060447</lat>
// ...
// </location>
// </geometry>
var doc = libxml.parseXmlString(xml),
lats = doc.find('//lat'),
lat1 = lats[0],
lat2 = lats[2],
txt1 = lat1.childNodes()[0],
txt2 = lat2.childNodes()[0];
console.log(txt1.toString());
console.log(txt2.toString());
console.log('-----------');
// this line will call xmlAddChild which will
// 1) add txt2 to the content of lat1
// 2) merge the (now two) TEXT nodes inside lat1
// 3) free the C struct representing txt2
lat1.addChild(txt2);
// and... this line will casue a SEGFAULT because
// libxmljs will try to access the freed struct
txt2.toString();
});