0

I want to search through multiple xml files and check for specific attribute values and every time i find the values i need, i want to copy the xml and so on

   <foo type="foo">
  <foo1 sport="Ghh" Code="349133" timestamp="1553189828.6330519">
    <rr result="false" Number="12" id="12" time="17:37:00">
      <Trap trap="1">
        <Runner id="493434" name="Dunb">
          <hh>
            <hh id="1" version="1" />
          </hh>
        </Runner>
    </rr>
  </foo1>
</foo>

So i want to find all the xml files and copy them with Code="349133" and rr id = "12"/

My code up to this point is the below

import os
import xml.etree.ElementTree as ET
from shutil import copyfile


def process(data):
    xml_obj = ET.fromstring(data)
    for rr in xml_obj:
        for k,v in rr.items():
            if k == 'Code' and v == '349133':
                return True
    return False


path = 'C:/Users/pp/.spyder-py3/data'
xml_files = os.listdir(path)
for xml_file in xml_files:
    xml_file_path = os.path.join(path, xml_file)
    fp = open(xml_file_path)
    data = fp.read()
    if process(data):
      //copyfile(src, dst)

I need help to add the id attribute on the def process(data) function in order to check it. And then i need your help on the copyfile because doesn't seem to work..

The copyfile was found from a post here on stackoverflow How do I copy a file in Python?

Thanks in advance

  • *"id attribute ... to check it"*: You should use [elementtree-xpath](https://docs.python.org/3/library/xml.etree.elementtree.html#elementtree-xpath) to find all `Elements` with ` – stovfl Mar 28 '19 at 15:35
  • Hey @stovfl thanks for your reply, i check the provided link but i am not sure how to modify the code and add the `# year' nodes that are children of nodes with name='Singapore' root.findall(".//*[@name='Singapore']/year")` Should i still use the loop ? – Panagiotis Ioannidis Mar 29 '19 at 09:58
  • There is no ` – stovfl Mar 29 '19 at 11:18

0 Answers0