Skip to content

Instantly share code, notes, and snippets.

@nathan130200
Last active August 5, 2020 19:14
Show Gist options
  • Save nathan130200/e9b671dcfea7f3c10665f0d607654d34 to your computer and use it in GitHub Desktop.
Save nathan130200/e9b671dcfea7f3c10665f0d607654d34 to your computer and use it in GitHub Desktop.
Simple POO for manage XML objects.
from xpnet import Attribute, Element
def run_server():
iq = Element("iq", "jabber:client")
iq.add_attribute("from", "my.server")
iq.add_attribute("to", "user@example/server")
iq.add_attribute("id", "uid00000005")
iq.add_attribute("type", "result")
test_service = Element("test_service")
test_service.add_attribute("host", "127.0.0.1")
test_service.add_attribute("port", "443")
query = Element("query", "urn:my:server")
query.add_child(test_service)
iq.add_child(query)
print(iq)
pass
if __name__ == "__main__":
run_server()
pass
class Attribute(object):
def __init__(self, name: str, value: str, prefix: str = None):
self.name = name
self.value = value
self.prefix = prefix
def qualified_name(self) -> str:
if self.prefix != None and len(self.prefix) > 0:
return "{}:{}".format(self.prefix, self.name)
return self.name
def __str__(self):
return "{}='{}'".format(self.qualified_name(), self.value)
class Element(object):
def __init__(self, name: str, namespace: str = None, prefix: str = None):
self.name = name
self.namespace = namespace
self.prefix = prefix
self._attributes = []
self._children = []
def qualified_name(self) -> str:
if self.prefix != None and len(self.prefix) > 0:
return "{}:{}".format(self.prefix, self.name)
return self.name
def add_attribute(self, name: str, value: str, prefix: str = None) -> Attribute:
attr = Attribute(name, value, prefix)
self._attributes.append(attr)
return attr
def add_child(self, child):
self._children.append(child)
def __str__(self):
raw = "<{}".format(self.qualified_name())
if self.namespace != None and len(self.namespace) > 0:
if self.prefix != None and len(self.prefix) > 0:
raw += " xmlns:{}='{}' ".format(self.prefix, self.namespace)
else:
raw += " xmlns='{}' ".format(self.namespace)
if len(self._attributes) > 0:
for attr in self._attributes:
raw += " {}".format(attr)
raw += " "
if len(self._children) == 0:
return raw + "/>"
else:
raw += ">"
for child in self._children:
raw += str(child)
return "{}</{}>".format(raw, self.qualified_name())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment