要获取element.tagName的问题。使用Python和xml.dom.minidom解析XML

时间:2015-03-19 09:52:21

标签: python xml parsing tagname

我用Python(xml.dom.minidom)解析XML,我无法得到节点的tagName。

翻译正在返回:

AttributeError: Text instance has no attribute 'tagName' 

当我尝试提取(例如)字符串'格式'来自节点:

<format>DVD</format>

我在Starckoverflow中找到了几个非常相似的帖子,但我仍然无法找到解决方案。

我知道可能有其他模块来处理这个问题,但我的目的是了解为什么它失败了。

非常感谢提前和最好的问候,

这是我的代码:

from xml.dom.minidom import parse
import xml.dom.minidom

# Open XML document
xml = xml.dom.minidom.parse("movies.xml")

# collection Node
collection_node = xml.firstChild

# movie Nodes
movie_nodes = collection_node.childNodes

for m in movie_nodes:

    if len(m.childNodes) > 0:
        print '\nMovie:', m.getAttribute('title')

        for tag in m.childNodes:
            print tag.tagName  # AttributeError: Text instance has no attribute 'tagName'
            for text in tag.childNodes:
                print text.data

这里是XML:

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
</collection>

类似帖子:

Get node name with minidom

Element.tagName for python not working

2 个答案:

答案 0 :(得分:6)

错误是由于元素节点之间的新行被认为是 TEXT_NODE 类型的不同节点(请参阅Node.nodeType),而 TEXT_NODE 不是&#39 ; t具有tagName属性。

您可以添加节点类型检查以避免从文本节点打印tagName

if tag.nodeType != tag.TEXT_NODE:
    print tag.tagName 

答案 1 :(得分:0)

这是用户在上面提出的修改代码的样子: har07

for tag in m.childNodes:
        if tag.nodeType != tag.TEXT_NODE:
        for text in tag.childNodes:
            print tag.tagName, ':', text.data

它现在就像一个魅力。