views:

7186

answers:

3

Hi Guys,

I am creating a GUI frontend for the Eve Online API in Python.

I have successfully pulled the XML data from their server.

I am trying to grab the value from a node called "name"

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name

This seems to find the node ok but the output is below:

[<DOM Element: name at 0x11e6d28>]

How could I get it to print the value of the node?

Cheers

+3  A: 

It should just be

name[0].nodeValue
eduffy
When I do name[0].nodeValue is gives back "None", just to test I passed it name[0].nodeName and it gave me "name" which is correct. Any ideas?
Eef
What about name[0].firstChild.nodeValue ?
eduffy
Just beware that you are not relying on implementation details in the xml-generator. There are no guarantees that the first child is *the* text node nor the *only* text node in any cases where there can be more than one child node.
Henrik Gustafsson
Why would anyone design a library in which the nodeValue of <name>Smith</name> is anything but "Smith"?! That little nugget cost me 30 minutes of tearing my hair out. I'm bald now. Thanks, minidom.
Assaf Lavie
+11  A: 

Probably something like this if it's the text part you want...

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')

print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)

The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.

<name>
  blabla
  <somestuff>asdf</somestuff>
  znylpx
</name>

You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.

Henrik Gustafsson
There so needs to be a built-in call for that.
romkyns
+1  A: 

I know this question is pretty old now, but I thought you might have an easier time with ElementTree

from xml.etree import ElementTree as ET
import datetime

f = ET.XML(data)

for element in f:
    if element.tag == "currentTime":
        # Handle time data was pulled
        currentTime = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
    if element.tag == "cachedUntil":
        # Handle time until next allowed update
        cachedUntil = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
    if element.tag == "result":
        # Process list of skills
        pass

I know that's not super specific, but I just discovered it, and so far it's a lot easier to get my head around than the minidom (since so many nodes are essentially white space).

For instance, you have the tag name and the actual text together, just as you'd probably expect:

>>> element[0]
<Element currentTime at 40984d0>
>>> element[0].tag
'currentTime'
>>> element[0].text
'2010-04-12 02:45:45'e
LarrikJ