Created
November 29, 2024 05:50
-
-
Save JEuler/655af77d97a667423b47f0660dcd476b to your computer and use it in GitHub Desktop.
Insert android:layoutDirection="ltr" to all xml in directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from lxml import etree | |
# List of tags to add android:layoutDirection="ltr" | |
ALLOWED_LAYOUT_TAGS = {"RelativeLayout", "LinearLayout", "FrameLayout", "ConstraintLayout"} | |
def process_xml_file(file_path): | |
try: | |
tree = etree.parse(file_path) | |
root = tree.getroot() | |
# Android namespace | |
android_namespace = "http://schemas.android.com/apk/res/android" | |
# Check if the root tag is one of the allowed ones | |
if root.tag in ALLOWED_LAYOUT_TAGS: | |
# Check if android:layoutDirection is already present | |
if f"{{{android_namespace}}}layoutDirection" not in root.attrib: | |
# Add android:layoutDirection="ltr" | |
root.set(f"{{{android_namespace}}}layoutDirection", "ltr") | |
tree.write(file_path, encoding="utf-8", xml_declaration=True) | |
print(f"Updated file: {file_path}") | |
else: | |
print(f"Skipped file (attribute already exists): {file_path}") | |
else: | |
print(f"Skipped file (root tag not suitable): {file_path}") | |
except etree.XMLSyntaxError as e: | |
print(f"XML parsing error in file {file_path}: {e}") | |
def process_directory(directory_path): | |
for root_dir, _, files in os.walk(directory_path): | |
for file in files: | |
if file.endswith(".xml"): | |
file_path = os.path.join(root_dir, file) | |
process_xml_file(file_path) | |
if __name__ == "__main__": | |
# Get directory from user input or use the current directory | |
directory = input("Enter the directory path with XML files (leave empty for the current directory): ").strip() | |
if not directory: | |
directory = os.getcwd() | |
if os.path.isdir(directory): | |
print(f"Processing files in directory: {directory}") | |
process_directory(directory) | |
else: | |
print("The specified directory does not exist.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment