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 => '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 => 'UTF-8')

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.



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'ext/libxml/ruby_xml_document.c', line 118

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));
  xdoc->_private = (void*) self;
  DATA_PTR(self) = xdoc;

  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.


12
13
14
# File 'lib/libxml/document.rb', line 12

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

.file(value, options = {}) ⇒ 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.

You may provide an optional hash table to control how the parsing is performed. Valid options are:

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 (|).


31
32
33
# File 'lib/libxml/document.rb', line 31

def self.file(value, options = {})
  Parser.file(value, options).parse
end

.io(value, options = {}) ⇒ 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 (|).


52
53
54
# File 'lib/libxml/document.rb', line 52

def self.io(value, options = {})
  Parser.io(value, options).parse
end

.string(value, options = {}) ⇒ Object

call-seq:

XML::Document.string(string)
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.

You may provide an optional hash table to control how the parsing is performed. Valid options are:

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 (|).


73
74
75
# File 'lib/libxml/document.rb', line 73

def self.string(value, options = {})
  Parser.string(value, options).parse
end

Instance Method Details

#canonicalize(xpath, mode, inclusive_ns_prefixes, comments) ⇒ String

Returns a string containing the canonicalized form of the document, or the subset specified by the xpath argument.

Returns:

  • (String)


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

static VALUE rxml_document_canonicalize(VALUE self, VALUE xpath_expr, VALUE mode, VALUE inclusive_ns_prefixes, VALUE comments) {
	Check_Type(mode, T_FIXNUM);
	Check_Type(comments, T_FIXNUM);

	xmlDocPtr xdoc;
	xmlXPathObjectPtr xpathObj;
	xmlXPathContextPtr xpathCtx;
	xmlChar *buffer = NULL;
	xmlNodeSetPtr nodes_to_canonize = NULL;
	xmlChar** prefixes = NULL;

  	Data_Get_Struct(self, xmlDoc, xdoc);

	if(TYPE(xpath_expr) == T_STRING) {
		VALUE expression = rb_check_string_type(xpath_expr);	
		xpathCtx = xmlXPathNewContext(xdoc);
		xpathCtx->node = xmlDocGetRootElement(xdoc);
		// Load document namespaces into the xpath context
  		xmlNsPtr *xnsArr = xmlGetNsList(xdoc, xpathCtx->node);
		if(xnsArr) {
    		xmlNsPtr xns = *xnsArr;
			while(xns) {
				if (xns->prefix)
					xmlXPathRegisterNs(xpathCtx, xns->prefix, xns->href);
				xns = xns->next;
			}
			xmlFree(xnsArr);
		}	
		xpathObj = xmlXPathEval((xmlChar*) StringValueCStr(expression), xpathCtx);
		if(xpathObj == NULL) {
			rxml_raise(xmlGetLastError());
		}
		nodes_to_canonize = xpathObj->nodesetval;
		if(nodes_to_canonize == NULL || nodes_to_canonize->nodeNr == 0) {
			//xpath didn't match anything, do nothing
			return Qnil;
		}
	}
	if(!NIL_P(inclusive_ns_prefixes)) {
		int i;
		struct RArray *ns_prefixes_array;
		ns_prefixes_array = RARRAY(inclusive_ns_prefixes);
		prefixes = (xmlChar**)malloc(sizeof(xmlChar**) * ns_prefixes_array->len + 1);
		for(i=0;i<ns_prefixes_array->len;i++) {
			VALUE prefix = ns_prefixes_array->ptr[i];
			prefixes[i] = (xmlChar*)StringValueCStr(prefix);
		}
		prefixes[ns_prefixes_array->len]=NULL;
	}

	int length = xmlC14NDocDumpMemory(xdoc,nodes_to_canonize,FIX2INT(mode),prefixes,FIX2INT(comments), &buffer);
	free(prefixes);
	VALUE result = rb_str_new((const char*)buffer, length);
	if(nodes_to_canonize) {
		xmlXPathFreeContext(xpathCtx);
		xmlXPathFreeObject(xpathObj);
	} xmlFree(buffer);
	return result;
}

#childObject

Get this document’s child node.



301
302
303
304
305
306
307
308
309
310
# File 'ext/libxml/ruby_xml_document.c', line 301

static VALUE rxml_document_child_get(VALUE self)
{
  xmlDocPtr xdoc;
  Data_Get_Struct(self, xmlDoc, 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)


318
319
320
321
322
323
324
325
326
327
# File 'ext/libxml/ruby_xml_document.c', line 318

static VALUE rxml_document_child_q(VALUE self)
{
  xmlDocPtr xdoc;
  Data_Get_Struct(self, xmlDoc, xdoc);

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

#compressionNumeric

Obtain this document’s compression mode identifier.

Returns:

  • (Numeric)


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'ext/libxml/ruby_xml_document.c', line 218

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

  int compmode;
  Data_Get_Struct(self, xmlDoc, 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.



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

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

  int compmode;
  Check_Type(num, T_FIXNUM);
  Data_Get_Struct(self, xmlDoc, 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)


278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'ext/libxml/ruby_xml_document.c', line 278

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

  Data_Get_Struct(self, xmlDoc, 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



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

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.



337
338
339
340
341
342
343
344
345
346
347
348
# File 'ext/libxml/ruby_xml_document.c', line 337

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

#debug_dumpObject



169
170
171
172
# File 'lib/libxml/document.rb', line 169

def debug_dump
  warn('Document#debug_dump is deprecated.  Use Document#debug instead.')
  self.debug
end

#debug_dump_headObject



174
175
176
177
# File 'lib/libxml/document.rb', line 174

def debug_dump_head
  warn('Document#debug_dump_head is deprecated.  Use Document#debug instead.')
  self.debug
end

#debug_format_dumpObject



179
180
181
182
# File 'lib/libxml/document.rb', line 179

def debug_format_dump
  warn('Document#debug_format_dump is deprecated.  Use Document#to_s instead.')
  self.to_s
end

#docbook_doc?Boolean

Specifies if this is an docbook node

Returns:

  • (Boolean)


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

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

#document?Boolean

Specifies if this is an DOCTYPE node

Returns:

  • (Boolean)


145
146
147
# File 'lib/libxml/document.rb', line 145

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

#dumpObject



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

def dump
  warn('Document#dump is deprecated.  Use Document#to_s instead.')
  self.to_s
end

#encodingXML::Encoding::UTF_8

Obtain the encoding specified by this document.



356
357
358
359
360
361
362
363
364
# File 'ext/libxml/ruby_xml_document.c', line 356

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

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

#encoding=(XML) ⇒ Object

Set the encoding for this document.



372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'ext/libxml/ruby_xml_document.c', line 372

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

  Data_Get_Struct(self, xmlDoc, 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.

Parameters:

  • xpath - The xpath expression as a string

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

  • Returns - XML::XPath::Object

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



118
119
120
# File 'lib/libxml/document.rb', line 118

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.



125
126
127
# File 'lib/libxml/document.rb', line 125

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

#format_dumpObject



164
165
166
167
# File 'lib/libxml/document.rb', line 164

def format_dump
  warn('Document#format_dump is deprecated.  Use Document#to_s instead.')
  self.to_s
end

#html_doc?Boolean

Specifies if this is an html node

Returns:

  • (Boolean)


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

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.

Returns:



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'ext/libxml/ruby_xml_document.c', line 393

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

  Data_Get_Struct(self, xmlDoc, xdoc);
  Data_Get_Struct(node, xmlNode, xnode);

  xresult = xmlDocCopyNode(xnode, xdoc, 1);

  if (xresult == NULL)
    rxml_raise(&xmlLastError);

  return rxml_node_wrap(xresult);
}

#lastObject

Obtain the last node.



415
416
417
418
419
420
421
422
423
424
425
# File 'ext/libxml/ruby_xml_document.c', line 415

static VALUE rxml_document_last_get(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

  return rxml_node_wrap(xdoc->last);
}

#last?Boolean

Determine whether there is a last node.

Returns:

  • (Boolean)


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

static VALUE rxml_document_last_q(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

#nextObject

Obtain the next node.



451
452
453
454
455
456
457
458
459
460
461
# File 'ext/libxml/ruby_xml_document.c', line 451

static VALUE rxml_document_next_get(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

  return rxml_node_wrap(xdoc->next);
}

#next?Boolean

Determine whether there is a next node.

Returns:

  • (Boolean)


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

static VALUE rxml_document_next_q(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

#typeNumeric

Obtain this node’s type identifier.

Returns:

  • (Numeric)


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

static VALUE rxml_document_node_type(VALUE self)
{
  xmlNodePtr xnode;
  Data_Get_Struct(self, xmlNode, xnode);
  return (INT2NUM(xnode->type));
}

#node_type_nameObject

Returns this node’s type name



130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/libxml/document.rb', line 130

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.



846
847
848
849
850
851
852
# File 'ext/libxml/ruby_xml_document.c', line 846

static VALUE rxml_document_order_elements(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);
  return LONG2FIX(xmlXPathOrderDocElems(xdoc));
}

#parentObject

Obtain the parent node.



500
501
502
503
504
505
506
507
508
509
510
# File 'ext/libxml/ruby_xml_document.c', line 500

static VALUE rxml_document_parent_get(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

  return rxml_node_wrap(xdoc->parent);
}

#parent?Boolean

Determine whether there is a parent node.

Returns:

  • (Boolean)


518
519
520
521
522
523
524
525
526
527
528
# File 'ext/libxml/ruby_xml_document.c', line 518

static VALUE rxml_document_parent_q(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

#prevObject

Obtain the previous node.



536
537
538
539
540
541
542
543
544
545
546
# File 'ext/libxml/ruby_xml_document.c', line 536

static VALUE rxml_document_prev_get(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

  return rxml_node_wrap(xdoc->prev);
}

#prev?Boolean

Determine whether there is a previous node.

Returns:

  • (Boolean)


554
555
556
557
558
559
560
561
562
563
564
# File 'ext/libxml/ruby_xml_document.c', line 554

static VALUE rxml_document_prev_q(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);

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

#readerObject



184
185
186
187
# File 'lib/libxml/document.rb', line 184

def reader
  warn('Document#reader is deprecated.  Use XML::Reader.document(self) instead.')
  XML::Reader.document(self)
end

#rootObject

Obtain the root node.



572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'ext/libxml/ruby_xml_document.c', line 572

static VALUE rxml_document_root_get(VALUE self)
{
  xmlDocPtr xdoc;

  xmlNodePtr root;

  Data_Get_Struct(self, xmlDoc, xdoc);
  root = xmlDocGetRootElement(xdoc);

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

  return rxml_node_wrap(root);
}

#root=(node) ⇒ Object

Set the root node.



593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'ext/libxml/ruby_xml_document.c', line 593

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

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

  Data_Get_Struct(self, xmlDoc, xdoc);
  Data_Get_Struct(node, xmlNode, xnode);

  xroot = xmlDocSetRootElement(xdoc, xnode);
  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)


625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'ext/libxml/ruby_xml_document.c', line 625

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 char *xencoding;
  int length;

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

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

  Data_Get_Struct(self, xmlDoc, 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 = xmlGetCharEncodingName((xmlCharEncoding)NUM2INT(rencoding));
      if (!xencoding)
        rb_raise(rb_eArgError, "Unknown encoding value: %d", NUM2INT(rencoding));
    }
  }

  length = xmlSaveFormatFileEnc(xfilename, xdoc, xencoding, indent);

  if (length == -1)
    rxml_raise(&xmlLastError);
  
  return (INT2NUM(length));
}

#standalone?Boolean

Determine whether this is a standalone document.

Returns:

  • (Boolean)


675
676
677
678
679
680
681
682
683
684
# File 'ext/libxml/ruby_xml_document.c', line 675

static VALUE rxml_document_standalone_q(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, 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)


703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
# File 'ext/libxml/ruby_xml_document.c', line 703

static VALUE rxml_document_to_s(int argc, VALUE *argv, VALUE self)
{ 
  VALUE result;
  VALUE options = Qnil;
  xmlDocPtr xdoc;
  int indent = 1;
  const char *xencoding = "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 = xmlGetCharEncodingName((xmlCharEncoding)NUM2INT(rencoding));
      if (!xencoding)
        rb_raise(rb_eArgError, "Unknown encoding value: %d", NUM2INT(rencoding));
    }
  }

  Data_Get_Struct(self, xmlDoc, xdoc);
  xmlDocDumpFormatMemoryEnc(xdoc, &buffer, &length, xencoding, indent);

  result = rb_str_new((const char*) buffer, length);
  xmlFree(buffer);
  return result;
}

#urlObject

Obtain this document’s source URL, if any.



747
748
749
750
751
752
753
754
755
756
# File 'ext/libxml/ruby_xml_document.c', line 747

static VALUE rxml_document_url_get(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);
  if (xdoc->URL == NULL)
    return (Qnil);
  else
    return (rb_str_new2((const char*) xdoc->URL));
}

#validate(dtd) ⇒ Object

Validate this document against the specified XML::DTD.



938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'ext/libxml/ruby_xml_document.c', line 938

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

  Data_Get_Struct(self, xmlDoc, xdoc);
  Data_Get_Struct(dtd, xmlDtd, xdtd);

  ctxt.userData = &error;
  ctxt.error = (xmlValidityErrorFunc) LibXML_validity_error;
  ctxt.warning = (xmlValidityWarningFunc) LibXML_validity_warning;

  ctxt.nodeNr = 0;
  ctxt.nodeTab = NULL;
  ctxt.vstateNr = 0;
  ctxt.vstateTab = NULL;

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

#validate_schema(relaxng) ⇒ Object

Validate this document against the specified XML::RelaxNG.

If a block is provided it is used as an error handler for validaten errors. The block is called with two argument, the message and a flag indication if the message is an error (true) or a warning (false).



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
# File 'ext/libxml/ruby_xml_document.c', line 903

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

  Data_Get_Struct(self, xmlDoc, xdoc);
  Data_Get_Struct(relaxng, xmlRelaxNG, xrelaxng);

  vptr = xmlRelaxNGNewValidCtxt(xrelaxng);

  xmlRelaxNGSetValidErrors(vptr,
      (xmlRelaxNGValidityErrorFunc) LibXML_validity_error,
      (xmlRelaxNGValidityWarningFunc) LibXML_validity_warning, NULL);

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

#validate_schema(schema) ⇒ Object

Validate this document against the specified XML::Schema.

If a block is provided it is used as an error handler for validaten errors. The block is called with two argument, the message and a flag indication if the message is an error (true) or a warning (false).



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

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

  Data_Get_Struct(self, xmlDoc, xdoc);
  Data_Get_Struct(schema, xmlSchema, xschema);

  vptr = xmlSchemaNewValidCtxt(xschema);

  xmlSchemaSetValidErrors(vptr,
      (xmlSchemaValidityErrorFunc) LibXML_validity_error,
      (xmlSchemaValidityWarningFunc) LibXML_validity_warning, NULL);

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

#versionObject

Obtain the XML version specified by this document.



764
765
766
767
768
769
770
771
772
773
# File 'ext/libxml/ruby_xml_document.c', line 764

static VALUE rxml_document_version_get(VALUE self)
{
  xmlDocPtr xdoc;

  Data_Get_Struct(self, xmlDoc, xdoc);
  if (xdoc->version == NULL)
    return (Qnil);
  else
    return (rb_str_new2((const char*) xdoc->version));
}

#xhtml?Boolean

Determine whether this is an XHTML document.

Returns:

  • (Boolean)


781
782
783
784
785
786
787
788
789
790
791
# File 'ext/libxml/ruby_xml_document.c', line 781

static VALUE rxml_document_xhtml_q(VALUE self)
{
  xmlDocPtr xdoc;
	xmlDtdPtr xdtd;
  Data_Get_Struct(self, xmlDoc, 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)


799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# File 'ext/libxml/ruby_xml_document.c', line 799

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

  int ret;

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