Answers for "python read xml file"

41

python read file

with open("file.txt", "r") as txt_file:
  return txt_file.readlines()
Posted by: Guest on November-30-2020
1

python read xml

from xml.dom import minidom

# parse an xml file by name
mydoc = minidom.parse('items.xml')

items = mydoc.getElementsByTagName('item')

# one specific item attribute
print('Item #2 attribute:')
print(items[1].attributes['name'].value)

# all item attributes
print('nAll attributes:')
for elem in items:
    print(elem.attributes['name'].value)

# one specific item's data
print('nItem #2 data:')
print(items[1].firstChild.data)
print(items[1].childNodes[0].data)

# all items data
print('nAll item data:')
for elem in items:
    print(elem.firstChild.data)
Posted by: Guest on April-11-2021
1

xml.etree create xml file

#code :
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")

#output : filename.xml -> 
"""
<root>
    <doc>
         <field1 name="blah">some value1</field1>
         <field2 name="asdfasd">some vlaue2</field2>
    </doc>
</root>
""""
Posted by: Guest on November-25-2020
3

python string to xml

import xml.etree.ElementTree as ET

root = ET.fromstring(country_data_as_string)
Posted by: Guest on June-18-2020
1

how to open xml file element tree

import xml.etree.ElementTree as ET

tree = ET.parse('filename.xml') #this gets the file into a tree structure
tree_root = tree.getroot() #this gives us the root element of the file
Posted by: Guest on October-30-2020
0

python read entire file

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()
Posted by: Guest on March-07-2020

Python Answers by Framework

Browse Popular Code Answers by Language