Reputation: 3138
I am trying to extract the author from this:
<icon>
<tags>
<tag>steam</tag>
</tags>
<author>Author Name</author>
<authorwebsite>http://www.domain.com/</authorwebsite>
<license>
Creative Commons (Attribution-Noncommercial-Share Alike 3.0 Unported)
</license>
<licensewebsite>http://creativecommons.org/licenses/by-nc-sa/3.0/</licensewebsite>
<iconset>Name</iconset>
<iconsetid>slug</iconsetid>
<attribution/>
<additionalsizes>
<icon>
<id>99633</id>
<size>128</size>
<tags/>
<image>
http://url1
</image>
</icon>
<icon>
<id>99633</id>
<size>256</size>
<tags/>
<image>
http://url2
</image>
</icon>
<icon>
<id>99633</id>
<size>512</size>
<tags/>
<image>
http://url3
</image>
</icon>
</additionalsizes>
</icon>
I tried:
name = dom.getElementsByTagName('author')
print name[0].firstChild.nodeValue
AttributeError: 'NoneType' object has no attribute 'nodeValue'
And:
name = dom.getElementsByTagName('author')
print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)
Returns empty string.
What's wrong? Thanks.
Upvotes: 0
Views: 141
Reputation: 1213
Easy peasy with lxml:
from lxml import etree
dom=etree.fromstring(XML_DOC)
dom.xpath('/icon/author/text()')[0]
returns 'Author Name'
Upvotes: 1
Reputation: 322
You forgot to get author from inside the icon tag
from xml.dom.minidom import parse
dom = parse('test.xml')
icon = dom.getElementsByTagName('icon')[0]
author = icon.getElementsByTagName('author')[0]
print author.firstChild.nodeValue
Upvotes: 2
Reputation: 13907
Using ElementTree, as suggested by @Martijn Pieters:
from xml.etree import ElementTree
tree = ElementTree.fromstring('<icon><author>Author Name</author></icon>')
print tree.find('author').text
Some more examples: http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/parse.html
Upvotes: 2