Python read xml file code example
Example 1: python read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
Example 2: python read xml
from xml.dom import minidom
mydoc = minidom.parse('items.xml')
items = mydoc.getElementsByTagName('item')
print('Item #2 attribute:')
print(items[1].attributes['name'].value)
print('\nAll attributes:')
for elem in items:
print(elem.attributes['name'].value)
print('\nItem #2 data:')
print(items[1].firstChild.data)
print(items[1].childNodes[0].data)
print('\nAll item data:')
for elem in items:
print(elem.firstChild.data)
Example 3: xml.etree create xml file
import xml.etree.cElementTree as ET
root = ET.Element("root")
doc = ET.SubElement(root, "doc")
ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"
tree = ET.ElementTree(root)
tree.write("filename.xml")
"""
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some vlaue2</field2>
</doc>
</root>
""""
Example 4: how to open xml file element tree
import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
tree_root = tree.getroot()
Example 5: python string to xml
import xml.etree.ElementTree as ET
root = ET.fromstring(country_data_as_string)
Example 6: python read entire file
with open('Path/to/file', 'r') as content_file:
content = content_file.read()