访问python minidom节点数据

时间:2012-10-19 17:43:24

标签: python xml minidom

import xml.dom.minidom

document = """\
<parent>
    <child1>value 1</child1>
    <child2>value 2</child2>
    <child3>value 3</child3>
</parent>
"""

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
        else:
            print "not text: "+ node.toxml()

    return ''.join(rc)

def handleParent(family):
    handleChild(family.getElementsByTagName("parent")[0])

def handleChild(parent):
    print getText(parent.childNodes)

dom = xml.dom.minidom.parseString(document)
handleParent(dom)

有谁能告诉我为什么这段代码不会抓取子标签之间的值?这是一个从这里http://docs.python.org/library/xml.dom.minidom.html

的精简示例

这是输出:

not text: <child1>value 1</child1>
not text: <child2>value 2</child2>
not text: <child3>value 3</child3>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你需要深入一个层次。文字是<childN>的孩子。

def getText(nodelist):
    rc = []
    for outer in nodelist:
        for node in outer.childNodes:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
            else:
                print "not text: "+ node.toxml()

    return ''.join(rc)
相关问题