Skip to content Skip to sidebar Skip to footer

Getting Text Between Xml Tags With Minidom

I have this sample xml document snippet barbaz I'm using python's minidom method from xml.dom. I

Solution 1:

So if you need to get the text out then you can do the following:

import xml.dom.minidom
document = "<root><foo>bar</foo><foo>baby</foo></root>"
dom = xml.dom.minidom.parseString(document)

defgetText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return''.join(rc)

defhandleTok(tokenlist):
    texts = ""for token in tokenlist:
        texts += " "+ getText(token.childNodes)
    return texts
foo = dom.getElementsByTagName("foo")
text = handleTok(foo)
print text

They have a good example on the site: http://docs.python.org/library/xml.dom.minidom.html

EDIT: For nested tags, check the example on the site.

Solution 2:

Here is how with ElementTree:

xml='''\
<root>
    <foo>bar</foo>
    <foo>baz</foo>
</root>'''import xml.etree.ElementTree as ET

for child in ET.fromstring(xml):
    print child.tag, child.text

Prints:

foo bar
foo baz

Post a Comment for "Getting Text Between Xml Tags With Minidom"