136
Vývoj / Re:Python a XML vracia none
« kdy: 15. 02. 2021, 19:12:13 »
python ma tu super vlastnost, ze si s nim muzes povidat. ja to delam tak ze kdyz mi neco nejde, tak si otevru python REPL, nahodim si tam minimalni priklad a pouzivam autocomplete a dir() funkci.
dalsi vec co je na pythonu super ze ma fakt dobrou dokumentaci - podival ses tam vubec?
https://docs.python.org/3/library/xml.etree.elementtree.html
dalsi vec co je na pythonu super ze ma fakt dobrou dokumentaci - podival ses tam vubec?
https://docs.python.org/3/library/xml.etree.elementtree.html
Kód: [Vybrat]
We can import this data by reading from a file:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
Or directly from a string:
root = ET.fromstring(country_data_as_string)
fromstring() parses XML from a string directly into an Element, which is the root element of the parsed tree. Other parsing functions may create an ElementTree. Check the documentation to be sure.
As an Element, root has a tag and a dictionary of attributes:
>>>
>>> root.tag
'data'
>>> root.attrib
{}
It also has children nodes over which we can iterate:
>>>
>>> for child in root:
... print(child.tag, child.attrib)
...
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}
Children are nested, and we can access specific child nodes by index:
>>>
>>> root[0][1].text
'2008'
