File: reflection.R

package info (click to toggle)
r-cran-xml 3.99-0.19-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,688 kB
  • sloc: ansic: 6,659; xml: 2,890; asm: 486; sh: 12; makefile: 2
file content (214 lines) | stat: -rw-r--r-- 5,259 bytes parent folder | download | duplicates (4)
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
# These are functions that examine an XML node and
# defines a class for each complex type.

#
# Need to make this work recursively
#


xmlToS4List =
function(from, class = xmlName(from), type = gsub("s$", "", xmlName(from)))
{
  new(class, xmlApply(from, as, type))
}

setGeneric("xmlToS4",
function(node, obj = new(xmlName(node)), ...)
 standardGeneric("xmlToS4")
)


setMethod("xmlToS4", "XMLInternalNode",
 function(node, obj = new(xmlName(node)), ...)
{
  if(is(obj, "character") && !isS4(obj))
    obj = new(obj)

#  if(xmlSize(node) == 1 && node[[1]])
#    return(as())
  ids = names(node)
  nodes = xmlChildren(node)
  obj = addXMLAttributes(obj, xmlAttrs(node, addNamespacePrefix = TRUE))

  slotIds = slotNames(obj)
  slots = getClass(class(obj))@slots


if(any(duplicated(ids))) {
     # experimenting with a different way of doing this.
     # Group the nodes with the same names and the process those.
  groupedNodes = split(nodes, ids)
  ids = intersect(names(groupedNodes), slotIds)
  for(i in ids) {
    tmp = groupedNodes[[i]]
    slot = slots[[i]]
    if(length(tmp) > 1) {
      val = lapply(tmp, convertNode, slot)
      val = if(isAtomicType(slot))
              unlist(val)
            else
              as(val, slot) # may be a specific sub-type of list
    } else {
       el = tmp[[1]]
       val = convertNode(el, slot)
    }
    slot(obj, i) <- val

  }
} else {

  # This was the original mechanism but it doesn't handle multiple nodes of the same name.
  for(i in seq(along = nodes)) {
     if(ids[i] %in% slotIds) {

       val = if(slots[[ids[i]]] == "character")
                 xmlValue(nodes[[i]])
             else
                tryCatch(as(nodes[[i]], slots[[ids[i]]]),
                         error = function(e)
                                    xmlToS4(nodes[[i]]))

       slot(obj, ids[i]) <- val #    xmlToS4(nodes[[i]])
     }
     # obj = addAttributes(obj,  xmlAttrs(nodes[[i]]))
  }
}

  obj
})

convertNode =
function(el, slot)
{
  if(slot == "character")
    xmlValue(el)
  else
    tryCatch(as(el, slot),
             error = function(e)
                         xmlToS4(el))
}

isAtomicType =
  #
  # check if className refers to a primitive/atomic type
  # or not.
function(className)
{
  atomicTypes = c("logical", "integer", "numeric", "character")
  if(className %in% atomicTypes)
    return(TRUE)

  k = getClassDef(className)
  length(intersect(names(k@contains), atomicTypes)) > 0
}


addXMLAttributes =
function(obj, attrs)
{
  slots = getClass(class(obj))@slots
  i = match(names(attrs), names(slots))

   # handle any namespace prefix
  if(any(is.na(i))) {
     w = grepl(":", names(attrs)) & is.na(i)
     if(any(w))
       i[which(w)] = match(gsub(".*:", "", names(attrs)[which(w)]), names(slots))
  }

  m = i
  if(any(!is.na(i))) {
    vals = structure(attrs[!is.na(i)], names = names(slots)[i [!is.na(i)] ])
    for(i in names(vals))
      slot(obj, i) <- as(vals[i], slots[[i]])
  }

  obj
}


makeClassTemplate =
  #
  # Get the class representation information to represent the contents of
  # an XML node.
  #
  #
function(xnode, types = character(), default = "ANY", className = xmlName(xnode),
         where = globalenv())
{
  user.types = types

  slots = names(xnode)
  types =
    xmlSApply(xnode, function(x) {
                      if(xmlSize(x) == 0)
                        default
                      else if(xmlSize(x) == 1 || is(x, "XMLInternalTextNode"))
                        "character"
                      else
                          xmlName(x)
                    })
  names(types) = slots
  types[names(xmlAttrs(xnode))] = "character"

  if(length(user.types))
    types[names(user.types)] = user.types

  coerce = sprintf("setAs('XMLAbstractNode', '%s', function(from) xmlToS4(from))", className)
  def = if(length(types))
           sprintf("setClass('%s',\n    representation(%s))", className,
                      paste(sQuote(names(types)), sQuote(types), sep = " = ", collapse = ",\n\t"))
        else
          sprintf("setClass('%s')", className)

  if(!is.null(where) && !(is.logical(where) && !where)) {
    eval(parse(text = def), envir = where)
    eval(parse(text = coerce), envir = where)
  }

  list(name = className, slots = types,
       def = def, coerce = coerce)
}



setAs("XMLAbstractNode", "integer",
      function(from)
       as.integer(xmlValue(from)))


setAs("XMLAbstractNode", "numeric",
      function(from)
       as.numeric(xmlValue(from)))

setAs("XMLAbstractNode", "character",
      function(from)
        xmlValue(from))

setAs("XMLAbstractNode", "URL",
      function(from)
        new("URL", xmlValue(from)))

setAs("XMLAbstractNode", "logical",
      function(from)
        as.logical(xmlValue(from)))

setAs("XMLAbstractNode", "Date",
      function(from)
        as.Date(xmlValue(from), "%Y-%m-%d"))

setAs("XMLAbstractNode", "POSIXct",
      function(from)
        as.POSIXct(strptime(xmlValue(from), "%Y-%m-%d %H:%M:%S")))



makeXMLClasses =
function(doc, omit = character(), eval = FALSE)
{
  a = getNodeSet(doc, "//*")
  ids = unique(sapply(a, xmlName))
  if(length(omit))
    ids = setdiff(ids, omit)
  lapply(ids, function(id) makeClassTemplate(getNodeSet(doc, sprintf("//%s", id))[[1]], where = eval))
}