/
xml_document.c
538 lines (444 loc) · 13.4 KB
/
xml_document.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#include <xml_document.h>
static int dealloc_node_i(xmlNodePtr key, xmlNodePtr node, xmlDocPtr doc)
{
switch(node->type) {
case XML_ATTRIBUTE_NODE:
xmlFreePropList((xmlAttrPtr)node);
break;
case XML_NAMESPACE_DECL:
xmlFree(node);
break;
default:
if(node->parent == NULL) {
xmlAddChild((xmlNodePtr)doc, node);
}
}
return ST_CONTINUE;
}
static void dealloc(xmlDocPtr doc)
{
xmlDeregisterNodeFunc func;
st_table *node_hash;
NOKOGIRI_DEBUG_START(doc);
func = xmlDeregisterNodeDefault(NULL);
node_hash = DOC_UNLINKED_NODE_HASH(doc);
st_foreach(node_hash, dealloc_node_i, (st_data_t)doc);
st_free_table(node_hash);
free(doc->_private);
doc->_private = NULL;
xmlFreeDoc(doc);
xmlDeregisterNodeDefault(func);
NOKOGIRI_DEBUG_END(doc);
}
static void recursively_remove_namespaces_from_node(xmlNodePtr node)
{
xmlNodePtr child ;
xmlAttrPtr property ;
xmlSetNs(node, NULL);
for (child = node->children ; child ; child = child->next)
recursively_remove_namespaces_from_node(child);
if (node->nsDef) {
xmlFreeNsList(node->nsDef);
node->nsDef = NULL;
}
if (node->properties != NULL) {
property = node->properties ;
while (property != NULL) {
if (property->ns) property->ns = NULL ;
property = property->next ;
}
}
}
/*
* call-seq:
* url
*
* Get the url name for this document.
*/
static VALUE url(VALUE self)
{
xmlDocPtr doc;
Data_Get_Struct(self, xmlDoc, doc);
if(doc->URL) return NOKOGIRI_STR_NEW2(doc->URL);
return Qnil;
}
/*
* call-seq:
* root=
*
* Set the root element on this document
*/
static VALUE set_root(VALUE self, VALUE root)
{
xmlDocPtr doc;
xmlNodePtr new_root;
xmlNodePtr old_root;
Data_Get_Struct(self, xmlDoc, doc);
old_root = NULL;
if(NIL_P(root)) {
old_root = xmlDocGetRootElement(doc);
if(old_root) {
xmlUnlinkNode(old_root);
NOKOGIRI_ROOT_NODE(old_root);
}
return root;
}
Data_Get_Struct(root, xmlNode, new_root);
/* If the new root's document is not the same as the current document,
* then we need to dup the node in to this document. */
if(new_root->doc != doc) {
old_root = xmlDocGetRootElement(doc);
if (!(new_root = xmlDocCopyNode(new_root, doc, 1))) {
rb_raise(rb_eRuntimeError, "Could not reparent node (xmlDocCopyNode)");
}
}
xmlDocSetRootElement(doc, new_root);
if(old_root) NOKOGIRI_ROOT_NODE(old_root);
return root;
}
/*
* call-seq:
* root
*
* Get the root node for this document.
*/
static VALUE root(VALUE self)
{
xmlDocPtr doc;
xmlNodePtr root;
Data_Get_Struct(self, xmlDoc, doc);
root = xmlDocGetRootElement(doc);
if(!root) return Qnil;
return Nokogiri_wrap_xml_node(Qnil, root) ;
}
/*
* call-seq:
* encoding= encoding
*
* Set the encoding string for this Document
*/
static VALUE set_encoding(VALUE self, VALUE encoding)
{
xmlDocPtr doc;
Data_Get_Struct(self, xmlDoc, doc);
doc->encoding = xmlStrdup((xmlChar *)StringValuePtr(encoding));
return encoding;
}
/*
* call-seq:
* encoding
*
* Get the encoding for this Document
*/
static VALUE encoding(VALUE self)
{
xmlDocPtr doc;
Data_Get_Struct(self, xmlDoc, doc);
if(!doc->encoding) return Qnil;
return NOKOGIRI_STR_NEW2(doc->encoding);
}
/*
* call-seq:
* version
*
* Get the XML version for this Document
*/
static VALUE version(VALUE self)
{
xmlDocPtr doc;
Data_Get_Struct(self, xmlDoc, doc);
if(!doc->version) return Qnil;
return NOKOGIRI_STR_NEW2(doc->version);
}
/*
* call-seq:
* read_io(io, url, encoding, options)
*
* Create a new document from an IO object
*/
static VALUE read_io( VALUE klass,
VALUE io,
VALUE url,
VALUE encoding,
VALUE options )
{
const char * c_url = NIL_P(url) ? NULL : StringValuePtr(url);
const char * c_enc = NIL_P(encoding) ? NULL : StringValuePtr(encoding);
VALUE error_list = rb_ary_new();
VALUE document;
xmlDocPtr doc;
xmlResetLastError();
xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);
doc = xmlReadIO(
(xmlInputReadCallback)io_read_callback,
(xmlInputCloseCallback)io_close_callback,
(void *)io,
c_url,
c_enc,
(int)NUM2INT(options)
);
xmlSetStructuredErrorFunc(NULL, NULL);
if(doc == NULL) {
xmlErrorPtr error;
xmlFreeDoc(doc);
error = xmlGetLastError();
if(error)
rb_exc_raise(Nokogiri_wrap_xml_syntax_error((VALUE)NULL, error));
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
document = Nokogiri_wrap_xml_document(klass, doc);
rb_iv_set(document, "@errors", error_list);
return document;
}
/*
* call-seq:
* read_memory(string, url, encoding, options)
*
* Create a new document from a String
*/
static VALUE read_memory( VALUE klass,
VALUE string,
VALUE url,
VALUE encoding,
VALUE options )
{
const char * c_buffer = StringValuePtr(string);
const char * c_url = NIL_P(url) ? NULL : StringValuePtr(url);
const char * c_enc = NIL_P(encoding) ? NULL : StringValuePtr(encoding);
int len = (int)RSTRING_LEN(string);
VALUE error_list = rb_ary_new();
VALUE document;
xmlDocPtr doc;
xmlResetLastError();
xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);
doc = xmlReadMemory(c_buffer, len, c_url, c_enc, (int)NUM2INT(options));
xmlSetStructuredErrorFunc(NULL, NULL);
if(doc == NULL) {
xmlErrorPtr error;
xmlFreeDoc(doc);
error = xmlGetLastError();
if(error)
rb_exc_raise(Nokogiri_wrap_xml_syntax_error((VALUE)NULL, error));
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
document = Nokogiri_wrap_xml_document(klass, doc);
rb_iv_set(document, "@errors", error_list);
return document;
}
/*
* call-seq:
* dup
*
* Copy this Document. An optional depth may be passed in, but it defaults
* to a deep copy. 0 is a shallow copy, 1 is a deep copy.
*/
static VALUE duplicate_node(int argc, VALUE *argv, VALUE self)
{
xmlDocPtr doc, dup;
VALUE level;
if(rb_scan_args(argc, argv, "01", &level) == 0)
level = INT2NUM((long)1);
Data_Get_Struct(self, xmlDoc, doc);
dup = xmlCopyDoc(doc, (int)NUM2INT(level));
if(dup == NULL) return Qnil;
dup->type = doc->type;
return Nokogiri_wrap_xml_document(rb_obj_class(self), dup);
}
/*
* call-seq:
* new(version = default)
*
* Create a new document with +version+ (defaults to "1.0")
*/
static VALUE new(int argc, VALUE *argv, VALUE klass)
{
xmlDocPtr doc;
VALUE version, rest, rb_doc ;
rb_scan_args(argc, argv, "0*", &rest);
version = rb_ary_entry(rest, (long)0);
if (NIL_P(version)) version = rb_str_new2("1.0");
doc = xmlNewDoc((xmlChar *)StringValuePtr(version));
rb_doc = Nokogiri_wrap_xml_document(klass, doc);
rb_obj_call_init(rb_doc, argc, argv);
return rb_doc ;
}
/*
* call-seq:
* remove_namespaces!
*
* Remove all namespaces from all nodes in the document.
*
* This could be useful for developers who either don't understand namespaces
* or don't care about them.
*
* The following example shows a use case, and you can decide for yourself
* whether this is a good thing or not:
*
* doc = Nokogiri::XML <<-EOXML
* <root>
* <car xmlns:part="http://general-motors.com/">
* <part:tire>Michelin Model XGV</part:tire>
* </car>
* <bicycle xmlns:part="http://schwinn.com/">
* <part:tire>I'm a bicycle tire!</part:tire>
* </bicycle>
* </root>
* EOXML
*
* doc.xpath("//tire").to_s # => ""
* doc.xpath("//part:tire", "part" => "http://general-motors.com/").to_s # => "<part:tire>Michelin Model XGV</part:tire>"
* doc.xpath("//part:tire", "part" => "http://schwinn.com/").to_s # => "<part:tire>I'm a bicycle tire!</part:tire>"
*
* doc.remove_namespaces!
*
* doc.xpath("//tire").to_s # => "<tire>Michelin Model XGV</tire><tire>I'm a bicycle tire!</tire>"
* doc.xpath("//part:tire", "part" => "http://general-motors.com/").to_s # => ""
* doc.xpath("//part:tire", "part" => "http://schwinn.com/").to_s # => ""
*
* For more information on why this probably is *not* a good thing in general,
* please direct your browser to
* http://tenderlovemaking.com/2009/04/23/namespaces-in-xml/
*/
VALUE remove_namespaces_bang(VALUE self)
{
xmlDocPtr doc ;
Data_Get_Struct(self, xmlDoc, doc);
recursively_remove_namespaces_from_node((xmlNodePtr)doc);
return self;
}
/* call-seq: doc.create_entity(name, type, external_id, system_id, content)
*
* Create a new entity named +name+.
*
* +type+ is an integer representing the type of entity to be created, and it
* defaults to Nokogiri::XML::EntityDecl::INTERNAL_GENERAL. See
* the constants on Nokogiri::XML::EntityDecl for more information.
*
* +external_id+, +system_id+, and +content+ set the External ID, System ID,
* and content respectively. All of these parameters are optional.
*/
static VALUE create_entity(int argc, VALUE *argv, VALUE self)
{
VALUE name;
VALUE type;
VALUE external_id;
VALUE system_id;
VALUE content;
xmlEntityPtr ptr;
xmlDocPtr doc ;
Data_Get_Struct(self, xmlDoc, doc);
rb_scan_args(argc, argv, "14", &name, &type, &external_id, &system_id,
&content);
xmlResetLastError();
ptr = xmlAddDocEntity(
doc,
(xmlChar *)(NIL_P(name) ? NULL : StringValuePtr(name)),
(int) (NIL_P(type) ? XML_INTERNAL_GENERAL_ENTITY : NUM2INT(type)),
(xmlChar *)(NIL_P(external_id) ? NULL : StringValuePtr(external_id)),
(xmlChar *)(NIL_P(system_id) ? NULL : StringValuePtr(system_id)),
(xmlChar *)(NIL_P(content) ? NULL : StringValuePtr(content))
);
if(NULL == ptr) {
xmlErrorPtr error = xmlGetLastError();
if(error)
rb_exc_raise(Nokogiri_wrap_xml_syntax_error((VALUE)NULL, error));
else
rb_raise(rb_eRuntimeError, "Could not create entity");
return Qnil;
}
return Nokogiri_wrap_xml_node(cNokogiriXmlEntityDecl, (xmlNodePtr)ptr);
}
static int block_caller(void * ctx, xmlNodePtr _node, xmlNodePtr _parent)
{
VALUE block;
VALUE node;
VALUE parent;
VALUE ret;
block = (VALUE)ctx;
node = Nokogiri_wrap_xml_node(Qnil, _node);
parent = _parent ? Nokogiri_wrap_xml_node(Qnil, _parent) : Qnil;
ret = rb_funcall(block, rb_intern("call"), 2, node, parent);
if(Qfalse == ret || Qnil == ret) return 0;
return 1;
}
/* call-seq:
* doc.canonicalize
* doc.canonicalize { |node, parent| ... }
*
* Canonicalize a document and return the results. Takes an optional block
* that takes two parameters the +node+ and that node's +parent+. The block
* must return a non-nil, non-false value if the +node+ passed in should be
* included in the canonicalized document.
*/
static VALUE canonicalize(VALUE self)
{
xmlDocPtr doc;
xmlOutputBufferPtr buf;
xmlC14NIsVisibleCallback cb = NULL;
void * ctx = NULL;
VALUE rb_cStringIO;
VALUE io;
Data_Get_Struct(self, xmlDoc, doc);
rb_cStringIO = rb_const_get_at(rb_cObject, rb_intern("StringIO"));
io = rb_class_new_instance(0, 0, rb_cStringIO);
buf = xmlAllocOutputBuffer(NULL);
buf->writecallback = (xmlOutputWriteCallback)io_write_callback;
buf->closecallback = (xmlOutputCloseCallback)io_close_callback;
buf->context = (void *)io;
if(rb_block_given_p()) {
cb = block_caller;
ctx = (void *)rb_block_proc();
}
xmlC14NExecute(doc, cb, ctx, 0, NULL, 0, buf);
xmlOutputBufferClose(buf);
return rb_funcall(io, rb_intern("string"), 0);
}
VALUE cNokogiriXmlDocument ;
void init_xml_document()
{
VALUE nokogiri = rb_define_module("Nokogiri");
VALUE xml = rb_define_module_under(nokogiri, "XML");
VALUE node = rb_define_class_under(xml, "Node", rb_cObject);
/*
* Nokogiri::XML::Document wraps an xml document.
*/
VALUE klass = rb_define_class_under(xml, "Document", node);
cNokogiriXmlDocument = klass;
rb_define_singleton_method(klass, "read_memory", read_memory, 4);
rb_define_singleton_method(klass, "read_io", read_io, 4);
rb_define_singleton_method(klass, "new", new, -1);
rb_define_method(klass, "root", root, 0);
rb_define_method(klass, "root=", set_root, 1);
rb_define_method(klass, "encoding", encoding, 0);
rb_define_method(klass, "encoding=", set_encoding, 1);
rb_define_method(klass, "version", version, 0);
rb_define_method(klass, "canonicalize", canonicalize, 0);
rb_define_method(klass, "dup", duplicate_node, -1);
rb_define_method(klass, "url", url, 0);
rb_define_method(klass, "create_entity", create_entity, -1);
rb_define_method(klass, "remove_namespaces!", remove_namespaces_bang, 0);
}
/* this takes klass as a param because it's used for HtmlDocument, too. */
VALUE Nokogiri_wrap_xml_document(VALUE klass, xmlDocPtr doc)
{
nokogiriTuplePtr tuple = (nokogiriTuplePtr)malloc(sizeof(nokogiriTuple));
VALUE rb_doc = Data_Wrap_Struct(
klass ? klass : cNokogiriXmlDocument,
0,
dealloc,
doc
);
VALUE cache = rb_ary_new();
rb_iv_set(rb_doc, "@decorators", Qnil);
rb_iv_set(rb_doc, "@node_cache", cache);
tuple->doc = (void *)rb_doc;
tuple->unlinkedNodes = st_init_numtable_with_size(128);
tuple->node_cache = cache;
doc->_private = tuple ;
rb_obj_call_init(rb_doc, 0, NULL);
return rb_doc ;
}