aboutsummaryrefslogtreecommitdiff
path: root/scripts/rpki/sax_utils.py
blob: 4d47f24aa9fef16709c4a06ffceec4e3540bd7e9 (plain) (blame)
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
# $Id$

import xml.sax

def snarf_attribute(obj, attrs, key, func=None):
  """
  Utility function to consolidate the steps needed to extract a field
  from the SAX XML parse and insert it as an object attribute of the
  same name.
  """

  if isinstance(key, list) or isinstance(key, tuple):
    for k in key:
      snarf_attribute(obj, attrs, k, func)
  else:
    try:
      val = attrs.getValue(key).encode("ascii")
      if func:
        val = func(val)
    except KeyError:
      val = None
    setattr(obj, key, val)

class handler(xml.sax.handler.ContentHandler):
  """
  SAX handler for RPKI protocols.  Handles a few tasks
  common to all of these protocols, needs to be subtyped
  to handle protocol-specific details.
  """

  def __init__(self):
    self.text = ""
    self.obj = None

  def startElementNS(self, name, qname, attrs):
    return self.startElement(name[1], attrs)

  def endElementNS(self, name, qname):
    return self.endElement(name[1])

  def characters(self, content):
    self.text += content

  def get_text(self):
    val = self.text.encode("ascii")
    self.text = ""
    return val

  def set_obj(self, obj):
    assert self.obj is None
    self.obj = obj