1
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>

谢谢您的帮助。

4

1 回答 1

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)
于 2012-10-19T18:16:43.110 回答