5

Python (xml.dom.minidom) で XML を解析していますが、ノードの tagName を取得できません。

インタプリタは以下を返します:

AttributeError: Text instance has no attribute 'tagName' 

ノードから文字列 'format' を (たとえば) 抽出しようとすると:

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

類似の投稿:

minidomでノード名を取得

Python の Element.tagName が機能しない

4

2 に答える 2

6

このエラーは、要素ノード間の新しい行が、タイプTEXT_NODE ( Node.nodeTypeを参照)の別のノードと見なされ、 TEXT_NODEに属性がないことがtagName原因でした。

tagNameテキスト ノードからの出力を回避するために、ノード タイプ チェックを追加できます。

if tag.nodeType != tag.TEXT_NODE:
    print tag.tagName 
于 2015-03-19T12:53:11.073 に答える
0

これは、ユーザーによって提案された上記の変更でコードがどのように見えるかです: har07 .

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

今では魅力のように機能します。

于 2015-03-19T14:01:58.843 に答える