Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help fixing my code. The code goes through xml documents in a directory a

ID: 3813168 • Letter: I

Question

I need help fixing my code. The code goes through xml documents in a directory and replaces the text in the text node. Right now it wont work becuase I use .findall. When I remove findall to make it look like this:

for pointers in root.findall("pointers"):
for pointer in pointers:
pointer = pointers.find("Pointer")
for text in pointer:
text = pointer.find("text").text

It only looks through one pointer and one text not all of them. There are two Pointer in pointers. I need to look through all of them and not just the first one. What would I change to fix this. It is written in python. Please help.

Code:

from lxml import etree

import glob, os

os.chdir("c:XMLFolder")
directory = os.getcwd()

findText = input("Enter text you would like to find: ")
replacementText = input ("Now enter the text you would like to replace with: ")

for files in glob.glob("*.xml"):
file = etree.parse(files)
root = file.getroot()
  
for pointers in root.findall("pointers"):
for pointer in pointers:
pointer = pointers.findall("Pointer")
for text in pointer:
text = pointer.findall("text").text
  
if findText in text:
text.replace(findText, replacementText)
print(findText + " has been replaced with " + replacementText)
  

  
file.write(files)

Explanation / Answer

try the following file = etree.parse(files) root = file.getroot() for e in root.getiterator(): try: e.text = e.text.replace('Pointer', replacementText) except AttributeError: pass file.write(file)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote