71 lines
1.4 KiB
Python
71 lines
1.4 KiB
Python
# Bryan Schumaker (10/24/2010)
|
|
|
|
import xml.dom.minidom as xml
|
|
|
|
def attributes(node):
|
|
attrs = dict()
|
|
for i in range(node.attributes.length):
|
|
item = node.attributes.item(i)
|
|
attrs[item.name] = item.nodeValue
|
|
return attrs
|
|
|
|
def children(doc):
|
|
list = []
|
|
for node in doc.childNodes:
|
|
if node.nodeType == node.TEXT_NODE:
|
|
if node.data.strip() == "":
|
|
continue
|
|
list += [node]
|
|
return list
|
|
|
|
def child(doc):
|
|
list = children(doc)
|
|
if len(list) > 0:
|
|
return list[0]
|
|
return None
|
|
|
|
def check_type(value):
|
|
if value.__class__ == unicode:
|
|
return value.encode("utf-8")
|
|
return str(value)
|
|
|
|
def add_child(doc, node, name, attrs = {}):
|
|
child = doc.createElement(name)
|
|
for attr in attrs:
|
|
value = check_type(attrs[attr])
|
|
child.setAttribute(attr, value)
|
|
node.appendChild(child)
|
|
return child
|
|
|
|
def add_text(doc, node, value):
|
|
value = check_type(value)
|
|
try:
|
|
child = doc.createTextNode( value )
|
|
node.appendChild(child)
|
|
return value
|
|
except Exception, e:
|
|
print e
|
|
print value, value.__class__
|
|
|
|
def get_elements(doc, tag):
|
|
return doc.getElementsByTagName(tag)
|
|
|
|
def find_attribute(doc, tag, attr, value):
|
|
for node in get_elements(doc, tag):
|
|
if attributes(node)[attr] == value:
|
|
return node
|
|
return None
|
|
|
|
def find_preferred_attribute(doc, tag, attr, values):
|
|
for value in values:
|
|
attr = find_attribute(doc, tag, attr, value)
|
|
if attr:
|
|
return attr
|
|
None
|
|
|
|
def new():
|
|
return xml.Document()
|
|
|
|
def parse(xml_file):
|
|
return xml.parse(xml_file)
|