25

我的 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=a[0].nodeValue

正确的输出应该是:

1
Bob
Nigel
2
Alice
Mary

但我得到的是:

1
None
None
2
None
None

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

4

5 回答 5

24

authortext的类型是 1 ( ELEMENT_NODE),通常你需要TEXT_NODE得到一个字符串。这将起作用

a.childNodes[0].nodeValue
于 2009-09-11T17:10:00.683 回答
6

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

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

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

text= ''.join(child.data for child in element.childNodes if child.nodeType==child.TEXT_NODE)

在 DOM Level 3 Core 中,您可以获得textContent可用于从元素内部递归获取文本的属性,但 minidom 不支持这一点(其他一些 Python DOM 实现支持)。

于 2009-09-11T17:10:16.717 回答
2

快速访问:

node.getElementsByTagName('author')[0].childNodes[0].nodeValue
于 2013-09-06T15:46:15.993 回答
2

由于每个作者总是有一个文本数据值,因此您可以使用 element.firstChild.data

dom = parseString(document)
conferences = dom.getElementsByTagName("conference")

# Each conference here is a node
for conference in conferences:
    conference_name = conference.getAttribute("name")
    print 
    print conference_name.upper() + " - "

    authors = conference.getElementsByTagName("author")
    for author in authors:
        print "  ", author.firstChild.data
    # for

    print
于 2016-02-09T12:43:14.653 回答
0

我玩了一下,这就是我要工作的:

# ...
authortext= a.childNodes[0].nodeValue
print authortext

导致输出:

C:\temp\py>xml2.py
1
鲍勃
奈杰尔
2
爱丽丝
玛丽

我无法确切告诉您为什么必须访问 childNode 才能获取内部文本,但至少这就是您要寻找的。

于 2009-09-11T17:05:12.693 回答