我有一个XML结构,它看起来像下面这样,但规模要大得多:
<root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author>
<author>
Mary
</author>
</conference>
</root>
为此,我使用了以下代码:
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
然而,打印出来的authortext是“None”。我试着使用下面这样的变体,但它导致我的程序崩溃。
authortext=a[0].nodeValue
正确的输出应该是:
1
Bob
Nigel
2
Alice
Mary
但我得到的是:
1
None
None
2
None
None
对如何解决这个问题有什么建议吗?
元素节点没有nodeValue。你得看看里面的文本节点。如果知道里面总是有一个文本节点,可以说
element.firstChild.data
(数据与文本节点的nodeValue相同)。注意:如果没有文本内容,则没有子文本节点,
element.firstChild
将为空,从而导致.data
访问失败。获取直接子文本节点内容的快速方法:
在DOM Level 3核心中,您获得了
textContent
属性,可以使用该属性递归地从元素内部获取文本,但是minidom不支持这个属性(其他一些Python DOM实现也支持)。您的
authortext
属于类型1(ELEMENT_NODE
),通常需要有TEXT_NODE
才能获取字符串。这样就行了快速访问:
相关问题 更多 >
编程相关推荐