2

I've found similar questions to this but can't find an exact answer and I'm having real difficulty getting this to work, so any help would be hugely appreciated.

I need to find a XML file in a folder structure that changes every time I run some automated tests.

This piece of code finds the file absolutely fine:

import xml.etree.ElementTree as ET
import glob

report = glob.glob('./Reports/Firefox/**/*.xml', recursive=True)
print(report)

I get a path returned. I then want to use that path, in the variable "report" and look for text within the XML file.

The following code finds the text fine IF the python file is in the same directory as the XML file. However, I need the python file to reside in the parent file and pass the "report" variable into the first line of code below.

tree = ET.parse("JUnit_Report.xml")
root = tree.getroot()

for testcase in root.iter('testcase'):
    testname = testcase.get('name')
    teststatus = testcase.get('status')
    print(testname, teststatus)

I'm a real beginner at Python, is this even possible?

S. Bunyard
  • 41
  • 3
  • By "I need the python file to reside in the parent file and pass the report variable", do you mean that you need the Python file to reside in the parent _directory_, and pass the _location_ of the report file to the `tree` variable? – Random Davis Nov 26 '18 at 16:37
  • [using regex can get a pattern matching text](https://stackoverflow.com/questions/18168684/parsing-xml-in-python-with-regex) If you need to get an element and its attribute. refer [element using lxml](https://stackoverflow.com/questions/12290091/reading-xml-file-and-fetching-its-attributes-value-in-python) – DevD Nov 26 '18 at 16:43
  • Yes @Random Davis, sorry, I should have been clearer on that – S. Bunyard Nov 26 '18 at 16:45
  • @S.Bunyard no worries, just make sure to edit any clarifications original question in order to provide the most assistance. – Random Davis Nov 26 '18 at 16:49

1 Answers1

2

Build the absolute path to your report file:

report = glob.glob('./Reports/Firefox/**/*.xml', recursive=True)
abs_path_to_report = os.path.abspath(report)

Pass that variable to whatever you want:

tree = ET.parse(abs_path_to_report )
Psytho
  • 3,313
  • 2
  • 19
  • 27