2044
Comment: finding elements
|
2380
adding element w/ text inside
|
Deletions are marked like this. | Additions are marked like this. |
Line 42: | Line 42: |
dom1 = parse("bar.xml") x = dom1.createElement("foo") # creates <foo /> dom1.childNodes[1].appendChild(x) # appends at end of 1st child's children print x.toxml() |
dom = parse("bar.xml") x = dom.createElement("foo") # creates <foo /> dom.childNodes[1].appendChild(x) # appends at end of 1st child's children print dom.toxml() |
Line 54: | Line 54: |
(researching) | {{{ #!python from xml.dom.minidom import parse dom = parse("bar.xml") x = dom.createElement("foo") # creates <foo /> txt = dom.createTextNode("hello, world!") # creates "hello, world!" x.appendChild(txt) # results in <foo>hello, world!</foo> dom.childNodes[1].appendChild(x) # appends at end of 1st child's children print dom.toxml() }}} |
Some notes on how to use xml.dom.minidom:
Examples of Use
- node.nodeName
- node.nodeValue
- node.childNodes
Find Elements
You can manually walk through the childNodes tree, comparing nodeNames.
You might be able to use getElementsByTagName as well:
getElementsByTagName, works recursively into the tree, I believe.
Add an Element
Create & add an XML element (Something like <foo />) to an XML document.
Add an Element with Text Inside
Create & add an XML element to an XML document, the element has text inside.
ex: <foo>hello, world!</foo>
1 from xml.dom.minidom import parse
2 dom = parse("bar.xml")
3 x = dom.createElement("foo") # creates <foo />
4 txt = dom.createTextNode("hello, world!") # creates "hello, world!"
5 x.appendChild(txt) # results in <foo>hello, world!</foo>
6 dom.childNodes[1].appendChild(x) # appends at end of 1st child's children
7 print dom.toxml()
Import a Node
You can use DOM 2 "importNode" to take part of one XML document, and put it into another XML document.
Links
[http://www.python.org/doc/2.3.2/lib/module-xml.dom.minidom.html Python 13.7, xml.dom.minidom] -- API reference
[http://www.faqs.org/docs/diveintopython/kgp_divein.html#kgp.divein Dive into Python, Chapter 5] -- works almost entirely out of the minidom API