1 class XMLNamespace(object):
2 '''A handy structure to represent names in an XML namespace.'''
4 def __init__(self, uri):
7 def __call__(self, tag):
8 return '{%s}%s' % (self.uri, tag)
10 def __contains__(self, tag):
11 return tag.startswith('{' + self.uri + '}')
14 return 'XMLNamespace(%r)' % self.uri
17 return '%s' % self.uri
19 def strip(self, qtag):
21 raise ValueError("Tag %s not in namespace %s" % (qtag, self.uri))
22 return qtag[len(self.uri) + 2:]
25 def split_tag(cls, tag):
31 return cls(tag[1:end]), tag[end + 1:]
34 def tagname(cls, tag):
35 return cls.split_tag(tag)[1]
38 class EmptyNamespace(XMLNamespace):
40 super(EmptyNamespace, self).__init__('')
42 def __call__(self, tag):
45 # some common namespaces we use
46 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
47 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
48 MARCRELNS = XMLNamespace('http://www.loc.gov/loc.terms/relators/')
50 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
51 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
56 MARCRELNS.uri: 'marcrel',
59 common_prefixes = dict((i[1], i[0]) for i in common_uris.items())
61 class NamespaceProxy(object):
63 def __init__(self, desc, uri):
64 object.__setattr__(self, 'uri', uri)
65 object.__setattr__(self, 'desc', desc)
67 def __getattr__(self, key):
68 return object.__getattribute__(self, 'desc')[self.uri, key]
70 def __setattr__(self, key, value):
71 object.__getattribute__(self, 'desc')[self.uri, key] = value
74 return ((XMLNamespace.tagname(attr.schema.name), attr.value) for attr in object.__getattribute__(self, 'desc').attrs.filter(schema__name__startswith="{%s}" % self.uri))
76 class NamespaceDescriptor(object):
78 def __init__(self, nsuri):
81 def __get__(self, instance, owner):
84 return NamespaceProxy(instance, self.nsuri)
86 def __set__(self, instance, value):