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:
CodePudding user response:
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.
CodePudding user response:
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'])