使用Python minidom读取XML并迭代每个节点

Gob*_*ffi 24 python xml parsing minidom

我有一个类似于以下的XML结构,但规模要大得多:

<root>
    <conference name='1'>
        <author>
            Bob
        </author>
        <author>
            Nigel
        </author>
    </conference>
    <conference name='2'>
        <author>
            Alice
        </author>
        <author>
            Mary
        </author>
    </conference>
</root>
Run Code Online (Sandbox Code Playgroud)

为此,我使用了以下代码:

dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
    conf_name=node.getAttribute('name')
    print conf_name
    alist=node.getElementsByTagName('author')
    for a in alist:
        authortext= a.nodeValue
        print authortext
Run Code Online (Sandbox Code Playgroud)

但是,打印出来的authortext是"None".我尝试使用如下所示的变体,但它会导致我的程序中断.

authortext=a[0].nodeValue
Run Code Online (Sandbox Code Playgroud)

正确的输出应该是:

1
Bob
Nigel
2
Alice
Mary
Run Code Online (Sandbox Code Playgroud)

但我得到的是:

1
None
None
2
None
None
Run Code Online (Sandbox Code Playgroud)

有关如何解决这个问题的任何建议?

Sil*_*ost 23

authortext的类型是1(ELEMENT_NODE),通常你需要TEXT_NODE得到一个字符串.这会奏效

a.childNodes[0].nodeValue
Run Code Online (Sandbox Code Playgroud)


bob*_*nce 6

元素节点没有nodeValue.您必须查看其中的Text节点.如果你知道里面总有一个文本节点可以说element.firstChild.data(数据与文本节点的nodeValue相同).

注意:如果没有文本内容,则没有子Text节点,并且element.firstChild将为null,导致.data访问失败.

快速获取直接子文本节点内容的方法:

text= ''.join(child.data for child in element.childNodes if child.nodeType==child.TEXT_NODE)
Run Code Online (Sandbox Code Playgroud)

在DOM Level 3 Core中,textContent您可以使用属性来递归地从Element内部获取文本,但minidom不支持此(其他一些Python DOM实现).