Class: LibXML::XML::Document

Inherits:
Object
  • Object
show all
Defined in:
ext/libxml/ruby_xml_document.c,
lib/libxml/document.rb,
ext/libxml/ruby_xml_document.c

Overview

The XML::Document class provides a tree based API for working with xml documents. You may directly create a document and manipulate it, or create a document from a data source by using an XML::Parser object.

To read a document from a file:

doc = XML::Document.file('my_file')

To use a parser to read a document:

parser = XML::Parser.file('my_file')
doc = parser.parse

To create a document from scratch:

doc = XML::Document.new()
doc.root = XML::Node.new('root_node')
doc.root << XML::Node.new('elem1')
doc.save(filename, :indent => true, :encoding => XML::Encoding::UTF_8)

To write a document to a file:

doc = XML::Document.new()
doc.root = XML::Node.new('root_node')
root = doc.root

root << elem1 = XML::Node.new('elem1')
elem1['attr1'] = 'val1'
elem1['attr2'] = 'val2'

root << elem2 = XML::Node.new('elem2')
elem2['attr1'] = 'val1'
elem2['attr2'] = 'val2'

root << elem3 = XML::Node.new('elem3')
elem3 << elem4 = XML::Node.new('elem4')
elem3 << elem5 = XML::Node.new('elem5')

elem5 << elem6 = XML::Node.new('elem6')
elem6 << 'Content for element 6'

elem3['attr'] = 'baz'

doc.save(filename, :indent => true, :encoding => XML::Encoding::UTF_8)

Constant Summary collapse

XML_C14N_1_0 =

Original C14N 1.0 spec

INT2NUM(XML_C14N_1_0)
XML_C14N_EXCLUSIVE_1_0 =

Exclusive C14N 1.0 spec

INT2NUM(XML_C14N_EXCLUSIVE_1_0)
XML_C14N_1_1 =

C14N 1.1 spec

INT2NUM(XML_C14N_1_1)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#XML::Document.initialize(xml_version = 1.0) ⇒ Object

Initializes a new XML::Document, optionally specifying the XML version.



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
# File 'ext/libxml/ruby_xml_document.c', line 111

static VALUE rxml_document_initialize(int argc, VALUE *argv, VALUE self)
{
  xmlDocPtr xdoc;
  VALUE xmlver;

  switch (argc)
  {
  case 0:
    xmlver = rb_str_new2("1.0");
    break;
  case 1:
    rb_scan_args(argc, argv, "01", &xmlver);
    break;
  default:
    rb_raise(rb_eArgError, "wrong number of arguments (need 0 or 1)");
  }

  Check_Type(xmlver, T_STRING);
  xdoc = xmlNewDoc((xmlChar*) StringValuePtr(xmlver));

  // Link the ruby object to the document and the document to the ruby object
  RTYPEDDATA_DATA(self) = xdoc;
  rxml_registry_register(xdoc, self);

  return self;
}

Class Method Details

.document(value) ⇒ Object

call-seq:

XML::Document.document(document) -> XML::Document

Creates a new document based on the specified document.

Parameters:

document - A preparsed document.


14
15
16
# File 'lib/libxml/document.rb', line 14

def self.document(value)
  Parser.document(value).parse
end

.file(path, encoding: nil, options: nil) ⇒ Object

call-seq:

XML::Document.file(path) -> XML::Document
XML::Document.file(path, encoding: XML::Encoding::UTF_8,
                         options: XML::Parser::Options::NOENT) -> XML::Document

Creates a new document from the specified file or uri.

Parameters:

path - Path to file
encoding - The document encoding, defaults to nil. Valid values
           are the encoding constants defined on XML::Encoding.
options - Parser options.  Valid values are the constants defined on
          XML::Parser::Options.  Mutliple options can be combined
          by using Bitwise OR (|).


33
34
35
# File 'lib/libxml/document.rb', line 33

def self.file(path, encoding: nil, options: nil)
  Parser.file(path, encoding: encoding, options: options).parse
end

.io(io, base_uri: nil, encoding: nil, options: nil) ⇒ Object

call-seq:

XML::Document.io(io) -> XML::Document
XML::Document.io(io, :encoding => XML::Encoding::UTF_8,
                     :options => XML::Parser::Options::NOENT
                     :base_uri="http://libxml.org") -> XML::Document

Creates a new document from the specified io object.

Parameters:

io - io object that contains the xml to parser
base_uri - The base url for the parsed document.
encoding - The document encoding, defaults to nil. Valid values
           are the encoding constants defined on XML::Encoding.
options - Parser options.  Valid values are the constants defined on
          XML::Parser::Options.  Mutliple options can be combined
          by using Bitwise OR (|).


54
55
56
# File 'lib/libxml/document.rb', line 54

def self.io(io, base_uri: nil, encoding: nil, options: nil)
  Parser.io(io, base_uri: base_uri, encoding: encoding, options: options).parse
end

.string(value, base_uri: nil, encoding: nil, options: nil) ⇒ Object

call-seq:

XML::Document.string(string) -> XML::Document
XML::Document.string(string, encoding: XML::Encoding::UTF_8,
                             options: XML::Parser::Options::NOENT
                             base_uri: "http://libxml.org") -> XML::Document

Creates a new document from the specified string.

Parameters:

string - String to parse
base_uri - The base url for the parsed document.
encoding - The document encoding, defaults to nil. Valid values
           are the encoding constants defined on XML::Encoding.
options  - Parser options.  Valid values are the constants defined on
           XML::Parser::Options.  Mutliple options can be combined
           by using Bitwise OR (|).


75
76
77
# File 'lib/libxml/document.rb', line 75

def self.string(value, base_uri: nil, encoding: nil, options: nil)
  Parser.string(value, base_uri: base_uri, encoding: encoding, options: options).parse
end

Instance Method Details

#canonicalize(*args) ⇒ Object



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
# File 'ext/libxml/ruby_xml_document.c', line 188

static VALUE
rxml_document_canonicalize(int argc, VALUE *argv, VALUE self)
{
  VALUE result = Qnil;
  xmlDocPtr xdoc;
  xmlChar *buffer = NULL;
  VALUE option_hash = Qnil;
  VALUE o_nodes = Qnil;

  // :comments option
  int comments = 0;
  // :mode option
  int c14n_mode = XML_C14N_1_0;
  // :inclusive_ns_prefixes option (ARRAY)

  xmlChar * inc_ns_prefixes_ptr[C14N_NS_LIMIT];

  // :nodes option (ARRAY)
  xmlNodePtr  node_ptr_array[C14N_NODESET_LIMIT];
  xmlNodeSet nodeset = {
    0, C14N_NODESET_LIMIT, NULL
  };

  /* At least one NULL value must be defined in the array or the extension will
   * segfault when using XML_C14N_EXCLUSIVE_1_0 mode.
   * API docs: "list of inclusive namespace prefixes ended with a NULL"
   */
  inc_ns_prefixes_ptr[0] = NULL;

  rb_scan_args(argc, argv, "01", &option_hash);
  // Do stuff if ruby hash passed as argument
  if (!NIL_P(option_hash)) 
  {
    VALUE o_comments = Qnil;
    VALUE o_mode = Qnil;
    VALUE o_i_ns_prefixes = Qnil;
    
    Check_Type(option_hash, T_HASH);

    o_comments = rb_hash_aref(option_hash, ID2SYM(rb_intern("comments")));
    comments = (RTEST(o_comments) ? 1 : 0);

    o_mode = rb_hash_aref(option_hash, ID2SYM(rb_intern("mode")));
    if (!NIL_P(o_mode)) 
    {
      Check_Type(o_mode, T_FIXNUM);
      c14n_mode = NUM2INT(o_mode);
      //TODO: clean this up
      //if (c14n_mode > 2) { c14n_mode = 0; }
      //mode_int = (NUM2INT(o_mode) > 2 ? 0 : NUM2INT(o_mode));
    }

    o_i_ns_prefixes = rb_hash_aref(option_hash, ID2SYM(rb_intern("inclusive_ns_prefixes")));
    if (!NIL_P(o_i_ns_prefixes)) 
    {
      int i;
      int p = 0; //pointer array index
      VALUE *list_in = NULL;
      long list_size = 0;

      Check_Type(o_i_ns_prefixes, T_ARRAY);
      list_in = RARRAY_PTR(o_i_ns_prefixes);
      list_size = RARRAY_LEN(o_i_ns_prefixes);

      if (list_size > 0) 
      {
        for(i=0; i < list_size; ++i) {
          if (p >= C14N_NS_LIMIT) { break; }

          if (RTEST(list_in[i])) 
          {
            if (TYPE(list_in[i]) == T_STRING) 
            {
              inc_ns_prefixes_ptr[p] = (xmlChar *)StringValueCStr(list_in[i]);
              p++;
            }
          }
        }
      }

      // ensure p is not out of bound
      p = (p >= C14N_NS_LIMIT ? (C14N_NS_LIMIT-1) : p);

      // API docs: "list of inclusive namespace prefixes ended with a NULL"
      // Set last element to NULL
      inc_ns_prefixes_ptr[p] = NULL;
    }
    //o_ns_prefixes will free at end of block

    o_nodes = rb_hash_aref(option_hash, ID2SYM(rb_intern("nodes")));
    if (!NIL_P(o_nodes))
    {
      if (CLASS_OF(o_nodes) == cXMLXPathObject)
      {
        /* Use the raw xmlNodeSet directly to preserve namespace nodes
           which cannot survive a roundtrip through Ruby objects */
        rxml_xpath_object *rxpop;
        TypedData_Get_Struct(o_nodes, rxml_xpath_object, &rxml_xpath_object_data_type, rxpop);
        if (rxpop->xpop->nodesetval)
        {
          nodeset.nodeNr = rxpop->xpop->nodesetval->nodeNr;
          nodeset.nodeMax = rxpop->xpop->nodesetval->nodeMax;
          nodeset.nodeTab = rxpop->xpop->nodesetval->nodeTab;
        }
      }
      else
      {
        int i;
        int p = 0;
        VALUE *list_in = NULL;
        long node_list_size = 0;

        Check_Type(o_nodes, T_ARRAY);
        list_in = RARRAY_PTR(o_nodes);
        node_list_size = RARRAY_LEN(o_nodes);

        for (i=0; i < node_list_size; ++i)
        {
          if (p >= C14N_NODESET_LIMIT) { break; }

          if (RTEST(list_in[i]))
          {
            xmlNodePtr node_ptr;
            TypedData_Get_Struct(list_in[i], xmlNode, &rxml_node_data_type, node_ptr);
            node_ptr_array[p] = node_ptr;
            p++;
          }
        }

        nodeset.nodeNr = (node_list_size > C14N_NODESET_LIMIT ?
                          C14N_NODESET_LIMIT :
                          (int)node_list_size);
        nodeset.nodeTab = node_ptr_array;
      }
    }
  }//option_hash

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  xmlC14NDocDumpMemory(xdoc,
                       (nodeset.nodeNr == 0 ? NULL : &nodeset),
                       c14n_mode,
                       inc_ns_prefixes_ptr,
                       comments,
                       &buffer);

  if (buffer)
  {
    result = rxml_new_cstr( buffer, NULL);
    xmlFree(buffer);
  }

  return result;
}

#childObject

Get this document’s child node.



432
433
434
435
436
437
438
439
440
441
# File 'ext/libxml/ruby_xml_document.c', line 432

static VALUE rxml_document_child_get(VALUE self)
{
  xmlDocPtr xdoc;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->children == NULL)
    return (Qnil);

  return rxml_node_wrap(xdoc->children);
}

#child?Boolean

Determine whether this document has a child node.

Returns:

  • (Boolean)


449
450
451
452
453
454
455
456
457
458
# File 'ext/libxml/ruby_xml_document.c', line 449

static VALUE rxml_document_child_q(VALUE self)
{
  xmlDocPtr xdoc;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->children == NULL)
    return (Qfalse);
  else
    return (Qtrue);
}

#compressionNumeric

Obtain this document’s compression mode identifier.

Returns:

  • (Numeric)


349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'ext/libxml/ruby_xml_document.c', line 349

static VALUE rxml_document_compression_get(VALUE self)
{
#ifdef HAVE_ZLIB_H
  xmlDocPtr xdoc;

  int compmode;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  compmode = xmlGetDocCompressMode(xdoc);
  if (compmode == -1)
  return(Qnil);
  else
  return(INT2NUM(compmode));
#else
  rb_warn("libxml not compiled with zlib support");
  return (Qfalse);
#endif
}

#compression=(num) ⇒ Object

Set this document’s compression mode.



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
# File 'ext/libxml/ruby_xml_document.c', line 374

static VALUE rxml_document_compression_set(VALUE self, VALUE num)
{
#ifdef HAVE_ZLIB_H
  xmlDocPtr xdoc;

  int compmode;
  Check_Type(num, T_FIXNUM);
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc == NULL)
  {
    return(Qnil);
  }
  else
  {
    xmlSetDocCompressMode(xdoc, NUM2INT(num));

    compmode = xmlGetDocCompressMode(xdoc);
    if (compmode == -1)
    return(Qnil);
    else
    return(INT2NUM(compmode));
  }
#else
  rb_warn("libxml compiled without zlib support");
  return (Qfalse);
#endif
}

#compression?Boolean

Determine whether this document is compressed.

Returns:

  • (Boolean)


409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'ext/libxml/ruby_xml_document.c', line 409

static VALUE rxml_document_compression_q(VALUE self)
{
#ifdef HAVE_ZLIB_H
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->compression != -1)
  return(Qtrue);
  else
  return(Qfalse);
#else
  rb_warn("libxml compiled without zlib support");
  return (Qfalse);
#endif
}

#context(nslist = nil) ⇒ Object

Returns a new XML::XPathContext for the document.

call-seq:

document.context(namespaces=nil) -> XPath::Context

Namespaces is an optional array of XML::NS objects



85
86
87
88
89
90
91
# File 'lib/libxml/document.rb', line 85

def context(nslist = nil)
  context = XPath::Context.new(self)
  context.node = self.root
  context.register_namespaces_from_node(self.root)
  context.register_namespaces(nslist) if nslist
  context
end

#debugObject

Print libxml debugging information to stdout. Requires that libxml was compiled with debugging enabled.



468
469
470
471
472
473
474
475
476
477
478
479
# File 'ext/libxml/ruby_xml_document.c', line 468

static VALUE rxml_document_debug(VALUE self)
{
#ifdef LIBXML_DEBUG_ENABLED
  xmlDocPtr xdoc;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  xmlDebugDumpDocument(NULL, xdoc);
  return Qtrue;
#else
  rb_warn("libxml was compiled without debugging support.");
  return Qfalse;
#endif
}

#docbook_doc?Boolean

Specifies if this is an docbook node

Returns:

  • (Boolean)


154
155
156
# File 'lib/libxml/document.rb', line 154

def docbook_doc?
  node_type == XML::Node::DOCB_DOCUMENT_NODE
end

#document?Boolean

Specifies if this is an document node

Returns:

  • (Boolean)


149
150
151
# File 'lib/libxml/document.rb', line 149

def document?
  node_type == XML::Node::DOCUMENT_NODE
end

#encodingXML::Encoding::UTF_8

Returns the LibXML encoding constant specified by this document.



487
488
489
490
491
492
493
494
495
# File 'ext/libxml/ruby_xml_document.c', line 487

static VALUE rxml_document_encoding_get(VALUE self)
{
  xmlDocPtr xdoc;
  const char *xencoding;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  xencoding = (const char*)xdoc->encoding;
  return INT2NUM(xmlParseCharEncoding(xencoding));
}

#encoding=(XML) ⇒ Object

Set the encoding for this document.



521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'ext/libxml/ruby_xml_document.c', line 521

static VALUE rxml_document_encoding_set(VALUE self, VALUE encoding)
{
  xmlDocPtr xdoc;
  const char* xencoding = xmlGetCharEncodingName((xmlCharEncoding)NUM2INT(encoding));

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->encoding != NULL)
    xmlFree((xmlChar *) xdoc->encoding);

  xdoc->encoding = xmlStrdup((xmlChar *)xencoding);
  return self;
}

#find(xpath, nslist = nil) ⇒ Object

Return the nodes matching the specified xpath expression, optionally using the specified namespace. For more information about working with namespaces, please refer to the XML::XPath documentation.

call-seq:

document.find(xpath, nslist=nil) -> XML::XPath::Object

Parameters:

  • xpath - The xpath expression as a string

  • namespaces - An optional list of namespaces (see XML::XPath for information).

document.find('/foo', 'xlink:http://www.w3.org/1999/xlink')

IMPORTANT - The returned XML::Node::Set must be freed before its associated document. In a running Ruby program this will happen automatically via Ruby’s mark and sweep garbage collector. However, if the program exits, Ruby does not guarantee the order in which objects are freed (see blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/17700). As a result, the associated document may be freed before the node list, which will cause a segmentation fault. To avoid this, use the following (non-ruby like) coding style:

nodes = doc.find('/header')
nodes.each do |node|
  ... do stuff ...
end

# nodes = nil # GC.start



122
123
124
# File 'lib/libxml/document.rb', line 122

def find(xpath, nslist = nil)
  self.context(nslist).find(xpath)
end

#find_first(xpath, nslist = nil) ⇒ Object

Return the first node matching the specified xpath expression. For more information, please refer to the documentation for XML::Document#find.



129
130
131
# File 'lib/libxml/document.rb', line 129

def find_first(xpath, nslist = nil)
  find(xpath, nslist).first
end

#html_doc?Boolean

Specifies if this is an html node

Returns:

  • (Boolean)


159
160
161
# File 'lib/libxml/document.rb', line 159

def html_doc?
  node_type == XML::Node::HTML_DOCUMENT_NODE
end

#import(node) ⇒ XML::Node

Creates a copy of the node that can be inserted into the current document.

IMPORTANT - The returned node MUST be inserted into the document. This is because the returned node refereces internal LibXML data structures owned by the document. Therefore, if the document is is freed before the the node is freed a segmentation fault will occur.

Returns:



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'ext/libxml/ruby_xml_document.c', line 547

static VALUE rxml_document_import(VALUE self, VALUE node)
{
  xmlDocPtr xdoc;
  xmlNodePtr xnode, xresult;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  TypedData_Get_Struct(node, xmlNode, &rxml_node_data_type, xnode);

  xresult = xmlDocCopyNode(xnode, xdoc, 1);

  if (xresult == NULL)
    rxml_raise(xmlGetLastError());

  return rxml_node_wrap(xresult);
}

#lastObject

Obtain the last node.



569
570
571
572
573
574
575
576
577
578
579
# File 'ext/libxml/ruby_xml_document.c', line 569

static VALUE rxml_document_last_get(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->last == NULL)
    return (Qnil);

  return rxml_node_wrap(xdoc->last);
}

#last?Boolean

Determine whether there is a last node.

Returns:

  • (Boolean)


587
588
589
590
591
592
593
594
595
596
597
# File 'ext/libxml/ruby_xml_document.c', line 587

static VALUE rxml_document_last_q(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->last == NULL)
    return (Qfalse);
  else
    return (Qtrue);
}

#nextObject

Obtain the next node.



605
606
607
608
609
610
611
612
613
614
615
# File 'ext/libxml/ruby_xml_document.c', line 605

static VALUE rxml_document_next_get(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->next == NULL)
    return (Qnil);

  return rxml_node_wrap(xdoc->next);
}

#next?Boolean

Determine whether there is a next node.

Returns:

  • (Boolean)


623
624
625
626
627
628
629
630
631
632
633
# File 'ext/libxml/ruby_xml_document.c', line 623

static VALUE rxml_document_next_q(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->next == NULL)
    return (Qfalse);
  else
    return (Qtrue);
}

#typeNumeric

Obtain this node’s type identifier.

Returns:

  • (Numeric)


641
642
643
644
645
646
# File 'ext/libxml/ruby_xml_document.c', line 641

static VALUE rxml_document_node_type(VALUE self)
{
  xmlDocPtr xdoc;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  return (INT2NUM(xdoc->type));
}

#node_type_nameObject

Returns this node’s type name



134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/libxml/document.rb', line 134

def node_type_name
  case node_type
  when XML::Node::DOCUMENT_NODE
    'document_xml'
  when XML::Node::DOCB_DOCUMENT_NODE
    'document_docbook'
  when XML::Node::HTML_DOCUMENT_NODE
    'document_html'
  else
    raise(UnknownType, "Unknown node type: %n", node.node_type);
  end
end

#order_elements!Object

Call this routine to speed up XPath computation on static documents. This stamps all the element nodes with the document order.



991
992
993
994
995
996
997
# File 'ext/libxml/ruby_xml_document.c', line 991

static VALUE rxml_document_order_elements(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  return LONG2FIX(xmlXPathOrderDocElems(xdoc));
}

#parentObject

Obtain the parent node.



654
655
656
657
658
659
660
661
662
663
664
# File 'ext/libxml/ruby_xml_document.c', line 654

static VALUE rxml_document_parent_get(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->parent == NULL)
    return (Qnil);

  return rxml_node_wrap(xdoc->parent);
}

#parent?Boolean

Determine whether there is a parent node.

Returns:

  • (Boolean)


672
673
674
675
676
677
678
679
680
681
682
# File 'ext/libxml/ruby_xml_document.c', line 672

static VALUE rxml_document_parent_q(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->parent == NULL)
    return (Qfalse);
  else
    return (Qtrue);
}

#prevObject

Obtain the previous node.



690
691
692
693
694
695
696
697
698
699
700
# File 'ext/libxml/ruby_xml_document.c', line 690

static VALUE rxml_document_prev_get(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->prev == NULL)
    return (Qnil);

  return rxml_node_wrap(xdoc->prev);
}

#prev?Boolean

Determine whether there is a previous node.

Returns:

  • (Boolean)


708
709
710
711
712
713
714
715
716
717
718
# File 'ext/libxml/ruby_xml_document.c', line 708

static VALUE rxml_document_prev_q(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  if (xdoc->prev == NULL)
    return (Qfalse);
  else
    return (Qtrue);
}

#rb_encodingEncoding

Returns the Ruby encoding specified by this document (available on Ruby 1.9.x and higher).

Returns:



505
506
507
508
509
510
511
512
513
# File 'ext/libxml/ruby_xml_document.c', line 505

static VALUE rxml_document_rb_encoding_get(VALUE self)
{
  xmlDocPtr xdoc;
  rb_encoding* rbencoding;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);

  rbencoding = rxml_xml_encoding_to_rb_encoding(mXMLEncoding, xmlParseCharEncoding((const char*)xdoc->encoding));
  return rb_enc_from_encoding(rbencoding);
}

#rootObject

Obtain the root node.



726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'ext/libxml/ruby_xml_document.c', line 726

static VALUE rxml_document_root_get(VALUE self)
{
  xmlDocPtr xdoc;
  xmlNodePtr root;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  root = xmlDocGetRootElement(xdoc);

  if (root == NULL)
    return (Qnil);

  return rxml_node_wrap(root);
}

#root=(node) ⇒ Object

Set the root node.



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'ext/libxml/ruby_xml_document.c', line 746

static VALUE rxml_document_root_set(VALUE self, VALUE node)
{
  xmlDocPtr xdoc;
  xmlNodePtr xnode;

  if (rb_obj_is_kind_of(node, cXMLNode) == Qfalse)
    rb_raise(rb_eTypeError, "must pass an XML::Node type object");

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  TypedData_Get_Struct(node, xmlNode, &rxml_node_data_type, xnode);

  if (xnode->doc != NULL && xnode->doc != xdoc)
    rb_raise(eXMLError, "Nodes belong to different documents.  You must first import the node by calling LibXML::XML::Document.import");

  xmlDocSetRootElement(xdoc, xnode);

  // Ruby no longer manages this nodes memory
  rxml_node_unmanage(xnode, node);

  return node;
}

#save(filename) ⇒ Integer #save(filename, : indent) ⇒ true

Saves a document to a file. You may provide an optional hash table to control how the string is generated. Valid options are:

:indent - Specifies if the string should be indented. The default value is true. Note that indentation is only added if both :indent is true and XML.indent_tree_output is true. If :indent is set to false, then both indentation and line feeds are removed from the result.

:encoding - Specifies the output encoding of the string. It defaults to the original encoding of the document (see #encoding. To override the orginal encoding, use one of the XML::Encoding encoding constants.

Overloads:

  • #save(filename) ⇒ Integer

    Returns:

    • (Integer)
  • #save(filename, : indent) ⇒ true

    Returns:

    • (true)


785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'ext/libxml/ruby_xml_document.c', line 785

static VALUE rxml_document_save(int argc, VALUE *argv, VALUE self)
{
  VALUE options = Qnil;
  VALUE filename = Qnil;
  xmlDocPtr xdoc;
  int indent = 1;
  const char *xfilename;
  const xmlChar *xencoding;
  int length;

  rb_scan_args(argc, argv, "11", &filename, &options);

  Check_Type(filename, T_STRING);
  xfilename = StringValuePtr(filename);

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  xencoding = xdoc->encoding;

  if (!NIL_P(options))
  {
    VALUE rencoding, rindent;
    Check_Type(options, T_HASH);
    rencoding = rb_hash_aref(options, ID2SYM(rb_intern("encoding")));
    rindent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));

    if (rindent == Qfalse)
      indent = 0;

    if (rencoding != Qnil)
    {
      xencoding = (const xmlChar*)xmlGetCharEncodingName((xmlCharEncoding)NUM2INT(rencoding));
      if (!xencoding)
        rb_raise(rb_eArgError, "Unknown encoding value: %d", NUM2INT(rencoding));
    }
  }

  length = xmlSaveFormatFileEnc(xfilename, xdoc, (const char*)xencoding, indent);

  if (length == -1)
    rxml_raise(xmlGetLastError());

  return (INT2NUM(length));
}

#standalone?Boolean

Determine whether this is a standalone document.

Returns:

  • (Boolean)


835
836
837
838
839
840
841
842
843
844
# File 'ext/libxml/ruby_xml_document.c', line 835

static VALUE rxml_document_standalone_q(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  if (xdoc->standalone)
    return (Qtrue);
  else
    return (Qfalse);
}

#to_sObject #to_s(: indent) ⇒ true

Converts a document, and all of its children, to a string representation. You may provide an optional hash table to control how the string is generated. Valid options are:

:indent - Specifies if the string should be indented. The default value is true. Note that indentation is only added if both :indent is true and XML.indent_tree_output is true. If :indent is set to false, then both indentation and line feeds are removed from the result.

:encoding - Specifies the output encoding of the string. It defaults to XML::Encoding::UTF8. To change it, use one of the XML::Encoding encoding constants.

Overloads:

  • #to_s(: indent) ⇒ true

    Returns:

    • (true)


863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
# File 'ext/libxml/ruby_xml_document.c', line 863

static VALUE rxml_document_to_s(int argc, VALUE *argv, VALUE self)
{
  VALUE result;
  VALUE options = Qnil;
  xmlDocPtr xdoc;
  int indent = 1;
  const xmlChar *xencoding = (const xmlChar*) "UTF-8";
  xmlChar *buffer;
  int length;

  rb_scan_args(argc, argv, "01", &options);

  if (!NIL_P(options))
  {
    VALUE rencoding, rindent;
    Check_Type(options, T_HASH);
    rencoding = rb_hash_aref(options, ID2SYM(rb_intern("encoding")));
    rindent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));

    if (rindent == Qfalse)
      indent = 0;

    if (rencoding != Qnil)
    {
      xencoding = (const xmlChar*)xmlGetCharEncodingName((xmlCharEncoding)NUM2INT(rencoding));
      if (!xencoding)
        rb_raise(rb_eArgError, "Unknown encoding value: %d", NUM2INT(rencoding));
    }
  }

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  xmlDocDumpFormatMemoryEnc(xdoc, &buffer, &length, (const char*)xencoding, indent);

  result = rxml_new_cstr(buffer, xencoding);
  xmlFree(buffer);
  return result;
}

#urlObject

Obtain this document’s source URL, if any.



907
908
909
910
911
912
913
914
915
916
# File 'ext/libxml/ruby_xml_document.c', line 907

static VALUE rxml_document_url_get(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  if (xdoc->URL == NULL)
    return (Qnil);
  else
    return (rxml_new_cstr( xdoc->URL, NULL));
}

#validate(dtd) ⇒ Object

Validate this document against the specified XML::DTD. If the document is valid the method returns true. Otherwise an exception is raised with validation information.



1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
# File 'ext/libxml/ruby_xml_document.c', line 1073

static VALUE rxml_document_validate_dtd(VALUE self, VALUE dtd)
{
  xmlValidCtxt ctxt;
  xmlDocPtr xdoc;
  xmlDtdPtr xdtd;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  TypedData_Get_Struct(dtd, xmlDtd, &rxml_dtd_data_type, xdtd);

  /* Setup context */
  memset(&ctxt, 0, sizeof(xmlValidCtxt));

  if (xmlValidateDtd(&ctxt, xdoc, xdtd))
  {
    return Qtrue;
  }
  else
  {
    rxml_raise(xmlGetLastError());
    return Qfalse;
  }
}

#validate_relaxng(relaxng) ⇒ Object

Validate this document against the specified XML::RelaxNG. If the document is valid the method returns true. Otherwise an exception is raised with validation information.



1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
# File 'ext/libxml/ruby_xml_document.c', line 1040

static VALUE rxml_document_validate_relaxng(VALUE self, VALUE relaxng)
{
  xmlRelaxNGValidCtxtPtr vptr;
  xmlDocPtr xdoc;
  xmlRelaxNGPtr xrelaxng;
  int is_invalid;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  TypedData_Get_Struct(relaxng, xmlRelaxNG, &rxml_relaxng_data_type, xrelaxng);

  vptr = xmlRelaxNGNewValidCtxt(xrelaxng);

  is_invalid = xmlRelaxNGValidateDoc(vptr, xdoc);
  xmlRelaxNGFreeValidCtxt(vptr);
  if (is_invalid)
  {
    rxml_raise(xmlGetLastError());
    return Qfalse;
  }
  else
  {
    return Qtrue;
  }
}

#validate_schema(schema) ⇒ Object

Validate this document against the specified XML::Schema. If the document is valid the method returns true. Otherwise an exception is raised with validation information.



1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'ext/libxml/ruby_xml_document.c', line 1007

static VALUE rxml_document_validate_schema(VALUE self, VALUE schema)
{
  xmlSchemaValidCtxtPtr vptr;
  xmlDocPtr xdoc;
  xmlSchemaPtr xschema;
  int is_invalid;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  TypedData_Get_Struct(schema, xmlSchema, &rxml_schema_type, xschema);

  vptr = xmlSchemaNewValidCtxt(xschema);

  is_invalid = xmlSchemaValidateDoc(vptr, xdoc);
  xmlSchemaFreeValidCtxt(vptr);
  if (is_invalid)
  {
    rxml_raise(xmlGetLastError());
    return Qfalse;
  }
  else
  {
    return Qtrue;
  }
}

#versionObject

Obtain the XML version specified by this document.



924
925
926
927
928
929
930
931
932
933
# File 'ext/libxml/ruby_xml_document.c', line 924

static VALUE rxml_document_version_get(VALUE self)
{
  xmlDocPtr xdoc;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  if (xdoc->version == NULL)
    return (Qnil);
  else
    return (rxml_new_cstr( xdoc->version, NULL));
}

#xhtml?Boolean

Determine whether this is an XHTML document.

Returns:

  • (Boolean)


941
942
943
944
945
946
947
948
949
950
951
# File 'ext/libxml/ruby_xml_document.c', line 941

static VALUE rxml_document_xhtml_q(VALUE self)
{
  xmlDocPtr xdoc;
  xmlDtdPtr xdtd;
  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  xdtd = xmlGetIntSubset(xdoc);
  if (xdtd != NULL && xmlIsXHTML(xdtd->SystemID, xdtd->ExternalID) > 0)
    return (Qtrue);
  else
    return (Qfalse);
}

#xincludeNumeric

Process xinclude directives in this document.

Returns:

  • (Numeric)


959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'ext/libxml/ruby_xml_document.c', line 959

static VALUE rxml_document_xinclude(VALUE self)
{
#ifdef LIBXML_XINCLUDE_ENABLED
  xmlDocPtr xdoc;

  int ret;

  TypedData_Get_Struct(self, xmlDoc, &rxml_document_data_type, xdoc);
  ret = xmlXIncludeProcess(xdoc);
  if (ret >= 0)
  {
    return(INT2NUM(ret));
  }
  else
  {
    rxml_raise(xmlGetLastError());
    return Qnil;
  }
#else
  rb_warn(
      "libxml was compiled without XInclude support.  Please recompile libxml and ruby-libxml");
  return (Qfalse);
#endif
}