Well, say you have found the element you want via the approach demonstrated above, and assigned it to the variable "sword":
# Get name element of sword
name = sword.getElementsByTagName("Name")[0]
# Change text in name
name.firstChild.replaceWholeText("Short Sword")
# Output the new xml
print xml.toxml()
This demonstrates that one can alter the XML DOM tree in place, and then output it as XML with all the changes made.
However, this isn't a very good way of doing things. A better way would be to have a "dump" and "load" method on each class:
import xml.dom.minidom as dom
class Sword:
def __init__(self, name):
self.name = name
def dump(self):
sword = dom.Element("Sword")
name = dom.Element("Name")
text = dom.Text()
text.replaceWholeText(self.name)
name.appendChild(text)
sword.appendChild(name)
return sword
@classmethod
def load(self, sword_element):
name = sword_element.getElementsByTagName("Name")[0]
return Sword(name.firstChild.wholeText)
But we can do even better than this:
import xml.dom.minidom as dom
def todom(sexpr):
if type(sexpr) is list or type(sexpr) is tuple:
node = dom.Element(sexpr[0])
for child in sexpr[1:]:
node.appendChild(todom(child))
else:
node = dom.Text()
node.replaceWholeText(str(sexpr))
return node
The above function converts s-expressions into XML, and we can use this to considerably shorten the code of our Sword class:
class Sword:
def __init__(self, name):
self.name = name
def dump(self):
return todom(("Sword" ("Name", self.name)))
@classmethod
def load(self, sword_element):
name = sword_element.getElementsByTagName("Name")[0]
return Sword(name.firstChild.wholeText)
There's probably quite a few XML serialisation libraries worth looking into as well... Though I'd personally look into YAML as an alternative to storing human-editable data to file.