访问python minidom节点d

2024-05-17 00:00:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是输出:

^{pr2}$

谢谢你的帮助。在


Tags: nodevaluedefxmldocumentdomparentgettext
1条回答
网友
1楼 · 发布于 2024-05-17 00:00:41

你需要深入一个层次。文本是<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)

相关问题 更多 >