Element.tagName for python not working

I have the following code in django and it returns an attribute error tagName:

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'

Does anyone know what is going on here?

+2
source share
3 answers

You should take a look at the xml you get. Probably the problem is that you get not only the tags in the root directory of the node, but also the text.

For instance:

>>> 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 the text node, and the second is the tag. Thus, it root.childNodes[0].tagNameraises the same exception that you get, and root.childNodes[1].tagNamereturns only tagas expected.

+1
source
node=root.childNodes[1]

node - DOM node. tagName. .

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

( "root" ) 3 . - node, tagName. data: root.childNodes[0].data

- , . Node tagName.

.

+1

childNodes (childNodes [0]) - . childNodes 1.

, 0 {} - . 1 {instance}, .

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

Example of childNodes items zero and one

0
source

All Articles