locoboy
locoboy

Reputation: 38960

Element.tagName for python not working

I have the following code in django and it's returning an error about tagName attribute:

def _parse_google_checkout_response(response_xml):
    redirect_url=''
    xml_doc=minidom.parseString(response_xml)
    root = xml_doc.documentElement
    node=root.childNodes[1]
    if node.tagName == 'redirect-url':
        redirect_url=node.firstChild.data
    if node.tagName == 'error-message':
        raise RuntimeError(node.firstChild.data)
    return redirect_url

Here's the error response:

Exception Type: AttributeError
Exception Value:    
Text instance has no attribute 'tagName'

Anyone have a clue as to what's going on here?

Upvotes: 2

Views: 2774

Answers (3)

accuya
accuya

Reputation: 1433

node=root.childNodes[1]

node is a DOM Text node. It has no tagName attribute. e.g.

>>> d = xml.dom.minidom.parseString('<root>a<node>b</node>c</root>')
>>> root = d.documentElement
>>> nodes = root.childNodes
>>> for node in nodes:
...   node
...
<DOM Text node "u'a'">
<DOM Element: node at 0xb706536c>
<DOM Text node "u'c'">

In the example above, the document element('root') has 3 child nodes. The 1st one is a text node, it has no tagName attribute. Instead, it's content can be accessed by 'data' attribute: root.childNodes[0].data

The 2nd one is an element, it contains other nodes. Node of this kind has a tagName attribute.

The 3rd one is similar to the 1st one.

Upvotes: 1

Brynn McCullagh
Brynn McCullagh

Reputation: 4143

The first item in childNodes (childNodes[0]) is the text. The first child element start at childNodes item 1.

In the image below, you can see that item 0 has {instance} Text next to it - as it is the text item. Below that, item 1 has {instance} Element, as it is an element item.

You can also see that childNodes[0] has the property 'wholeText' (representing the text) while childNodes item 1 has the property 'tagName', which is the name of the first child element. So you can't try to get the tagName property off childNodes[0].

Example of childNodes items zero and one

Upvotes: 0

jcollado
jcollado

Reputation: 40414

You have to take a look at the xml that you're receiving. The problem is probably that you're getting not only tags in the root node, but also text.

For example:

>>> xml_doc = minidom.parseString('<root>text<tag></tag></root>')
>>> root = xml.documentElement
>>> root.childNodes
[<DOM Text node "u'root node '...">, <DOM Element: tag at 0x2259368>]

Note that, in my example, the first node is a text node and the second one is a tag. Thus, root.childNodes[0].tagName raises the very same exception you're getting, while root.childNodes[1].tagName returns just tag as expected.

Upvotes: 1

Related Questions