2

I I have a xml file like this

<?xml version="1.0" encoding="UTF-8"?>
<Automation_Config>
    <Path>
        <Log>.\SERVER.log</Log>
        <Flag_Path>.\Flag</Flag_Path>
        <files>.\PO</files>
    </Path>

</Automation_Config>

I want to read the xml file and get the element of those, and assign to variable.

I tried this, but I can not get the element of Log.

import xml.dom.minidom
def main ():
    Load_XML = xml.dom.minidom.parse('D:/Config.xml')
    print (Load_XML.nodeName)
    print (Load_XML.firstChild.tagName)

    Log = Load_XML.getElementsByTagName ("Log")
    print (Log)

main()
3
  • I strongly advice against using xml.dom.minidom. Unless you have a very specific need to work with the very minimal and basic W3C DOM API, you want to be using the xml.etree.ElementTree API instead. The DOM API is aimed as a minimal common ground between lots of programming languages, many not nearly as expressive as Python. As a consequence, it is very, very, very tedious to have to work with.
    – Martijn Pieters
    Aug 5, 2019 at 13:03
  • With the ElementTree API, getting the string contents of the first Log element is as trivial as tree = ET.parse(filename) then value = tree.find(".//Log").text.
    – Martijn Pieters
    Aug 5, 2019 at 13:07

2 Answers 2

3

Use ElementTree:

import xml.etree.ElementTree as ET
tree = ET.parse('Config.xml')
root = tree.getroot()
print(root.findall('.//Log'))

Output:

pawel@pawel-XPS-15-9570:~/test$ python parse_xml.py 
[<Element 'Log' at 0x7fb3f2eee9f
0

Below:

import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Automation_Config>
    <Path>
        <Log>.\SERVER.log</Log>
        <Flag_Path>.\Flag</Flag_Path>
        <files>.\PO</files>
    </Path>

</Automation_Config>'''

root = ET.fromstring(xml)
for idx,log_element in enumerate(root.findall('.//Log')):
  print('{}) Log value: {}'.format(idx,log_element.text))

output

0) Log value: .\SERVER.log

Not the answer you're looking for? Browse other questions tagged or ask your own question.