Question

I have an object C which inherits class B which inherits class A, along with a method for each class, e.g.,

setClass("A", representation(a = 'numeric'))
setClass("B", representation(b = 'numeric'), contains="A")
setClass("C", representation(c = 'numeric'), contains="B")

and methods

setGeneric("toXML", function(obj, node) standardGeneric("toXML"))
setMethod("toXML", 
          signature("A", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, a = obj@a))
setMethod("toXML", 
          signature("B", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, b = obj@b))
setMethod("toXML", 
          signature("C", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, c = obj@c))

That is, each class represents a possible attribute an XML node can have.
I want to write a method (or coercion) that would perform these functions for all matching classes.

Of course the way I've written it, doing

library(XML)
obj <- new("C", a = 1, b = 2, c = 3)
toXML(obj, newXMLNode("node"))

Just returns:

<node c="3"/> 

Instead of

<node a="1" b="2" c="3"/> 

What would be a good way to go about this?

Was it helpful?

Solution

Maybe by using callNextMethod()?

setGeneric("toXML", function(obj, node) standardGeneric("toXML"))
setMethod("toXML", 
          signature("A", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, a = obj@a))
setMethod("toXML", 
          signature("B", "XMLInternalElementNode"), 
          function(obj, node) {
              node <- callNextMethod()            ## <- Line I added
              addAttributes(node, b = obj@b)
              })
setMethod("toXML", 
          signature("C", "XMLInternalElementNode"), 
          function(obj, node) {
              node <- callNextMethod()            ## <- Line I added 
              addAttributes(node, c = obj@c)
          })

## Trying it out
obj <- new("C", a = 1, b = 2, c = 3)
toXML(obj, newXMLNode("node"))
# <node a="1" b="2" c="3"/> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top