0

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

Francis Bacon
  • 4,080
  • 1
  • 37
  • 48
  • So this is about pretty-printing? – mzjn Oct 13 '22 at 04:57
  • See https://stackoverflow.com/q/749796/407651, https://stackoverflow.com/q/5086922/407651 – mzjn Oct 13 '22 at 05:08
  • @mzjn not sure, but anyway `pretty_print=True` does not work for it. – Francis Bacon Oct 14 '22 at 14:59
  • Did you try this? https://stackoverflow.com/a/9612463/407651 – mzjn Oct 14 '22 at 15:25
  • appending `remove_blank_text ` into `xml_tree.write(destination_xml_file_full_path, encoding='UTF-8', xml_declaration=False, pretty_print=True)` will be runtime error. Do you know how to combine `remove_blank_text` with the existing one? @mzjn – Francis Bacon Oct 17 '22 at 15:12
  • Look closely at the linked answer again. `remove_blank_text=True` is a parameter on the `parser` object. It does not belong in the `write()` method. – mzjn Oct 17 '22 at 15:37

0 Answers0