I use the following codes to try to append the element under tag resources
.
parser = Et.XMLParser(strip_cdata=False)
xml_tree = Et.parse(destination_xml_file_full_path, parser=parser)
xml_tree_root_element = xml_tree.getroot()
string_element = Et.Element('string')
string_element.set('name', string_id)
string_element.text = ''
xml_tree_root_element.append(string_element)
# Write the modified xml file.
xml_tree.write(destination_xml_file_full_path, encoding='UTF-8', xml_declaration=False, pretty_print=True)
Expected:
<resources>
<string name="cbp_payment_successful">Payment Successful</string>
...
<string name="string id"></string> // wanna to add this line of code
</resources>
Actual:
<resources>
<string name="cbp_payment_successful">Payment Successful</string>
...
<string name="string id"></string> // wanna to add this line of code</resources>
I already know I can use Android Studio reformat to achieve that, but is there any better way to achieve it only using Python?
Idea 1:
find the resources tag and append an element under the tag, but is there any API for that?
Idea 2:
find the last string element, and get the root of the string element, and use insert