[libxml-devel] Subclassing XML::Document?

Charlie Savage cfis at savagexi.com
Wed Aug 27 12:44:30 EDT 2008


Hey Mark,

> I'd like to create a subclass of XML::Document. However, I'm having 
> trouble figuring out how I would instantiate my subclass because parsing 
> requires Parser.parse() which returns an XML::Document instead of 
> My::Subclass. Unfortunately, Ruby doesn't have a way of changing the 
> class of an object.

Hmm, interesting question.  One approach is what Dan said.

The way the code works now (simplified):


ruby_xml_parser_parse(VALUE self) {
   ruby_xml_parser *rxp;
   ruby_xml_parser_context *rxpc;
   xmlDocPtr xdp;
   VALUE doc;

   Data_Get_Struct(self, ruby_xml_parser, rxp);
   Data_Get_Struct(rxp->ctxt, ruby_xml_parser_context, rxpc);
   xmlParseDocument(rxpc->ctxt)
   xdp = rxpc->ctxt->myDoc;
   return ruby_xml_document_wrap(xdp);
}

The issue is the last line - it takes the libxml document object and 
wraps it by creating a new Ruby document object.  Somehow that would 
have to change to allow the user to specify what document to create.

The most obvious way of doing this is adding a parameter to the parse 
method that specifies what class to create:

XML::Parser.string('foo').parse(MyCustomDocument) and then also add a 
parameter to the ruby_xml_document_wrap method.  That would be easy to 
do, but seems a bit kludgy.  But I have no better ideas...

Charlie
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3237 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://rubyforge.org/pipermail/libxml-devel/attachments/20080827/e7d5db37/attachment-0001.bin>


More information about the libxml-devel mailing list