-1

I'm looking to print ALL elements witch have these three specific attributes: 'name', 'top', 'left' from an XML file. So far i can do it manualy by firstly printing all tags:

for elm in root.findall("./"): print(elm.tag)

and then i can go throgh what it prints one by one for example like:

for elm in root.findall("./momentaryButton"): print(elm.attrib['name'],elm.attrib['top'],elm.attrib['left']) etc.

I have a problem in writing a program which will find all the lines containing the XML tag properties "name", "top" and "left" and will write value of this properties in console all at once. Is there a way to do it?

I'm pasting an XML file below:

Mixhalo
  • 33
  • 1
  • 5

2 Answers2

1

I believe you are looking for something like

for elm in root.findall(".//*"): 
    if 'left' and 'name' and 'top' in elm.attrib.keys():
        for k,v in  elm.attrib.items():
            print(k,":",v)
        print('------------')

The output should all the attributes and their values for those elements which have all the three specified attributes.

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
  • Thanks again, I guess in my last post I missunderstood You, I was trying to make a program which will find all the lines containing xml tag properties "name", "top" and "left" and will write value of this properties in console, e.g: MomentaryPushButton1 50 10 (Program is printing only those 3 values - name, top and left) in every element that has those attributes – Mixhalo Feb 23 '22 at 23:48
0

An XPath to select the elements that have the attribute @name, or @top, or @left:

//*[@name or @top or @left]

Applied to your code:

for elm in root.findall("//*[@name or @top or @left]"): 
print(elm.attrib['name'], elm.attrib['top'], elm.attrib['left'])
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • File "C:\Users\mixha\OneDrive\Desktop\task_Obiedzinski\task_1_Obiedzinski.py", line 12, in from pathlib import Path File "C:\Users\mixha\miniconda3\lib\xml\etree\ElementPath.py", line 395, in findall return list(iterfind(elem, path, namespaces)) File "C:\Users\mixha\miniconda3\lib\xml\etree\ElementPath.py", line 368, in iterfind selector.append(ops[token[0]](next, token)) File "C:\Users\mixha\miniconda3\lib\xml\etree\ElementPath.py", line 321, in prepare_predicate raise SyntaxError("invalid predicate") File "", line None SyntaxError: invalid predicate – Mixhalo Feb 23 '22 at 22:11
  • This is an error that occured – Mixhalo Feb 23 '22 at 22:11
  • 1
    Maybe it doesn't like the `or` criteria. Apparently, the XPath support is limited https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support others have reported issues, and found lxml to work for them https://stackoverflow.com/a/33830958/14419 – Mads Hansen Feb 23 '22 at 22:45