본문 바로가기

코딩 농장

xml map 만드는 파이썬 코드

import xml.etree.ElementTree as ET

class XMLTag:
    def __init__(self, name, value="", parent=None):
        self.name = name
        self.value = value
        self.attributes = {}
        self.children = []
        self.parent = parent

    def add_attribute(self, key, value):
        self.attributes[key] = value

    def add_child(self, child):
        child.parent = self
        self.children.append(child)

    def set_value(self, value):
        self.value = value

    def set_attribute(self, key, value):
        if key in self.attributes:
            self.attributes[key] = value
        else:
            print(f"Attribute {key} does not exist.")

    def to_string(self, depth=0):
        indent = "\t" * depth
        attr_str = " ".join([f'{key}="{value}"' for key, value in self.attributes.items()])
        if self.children:
            children_str = "\n".join([child.to_string(depth + 1) for child in self.children])
            return f"{indent}<{self.name} {attr_str}>{self.value}\n{children_str}\n{indent}</{self.name}>"
        else:
            if self.value:
                return f"{indent}<{self.name} {attr_str}>{self.value}</{self.name}>"
            else:
                if self.name == "root":
                    return f"{indent}<{self.name}></{self.name}>"
                return f"{indent}<{self.name} {attr_str.strip()}/>"  # Strip any extra spaces

    def to_element(self):
        element = ET.Element(self.name, self.attributes)
        if self.value:
            element.text = self.value
        for child in self.children:
            element.append(child.to_element())
        return element

class XMLBuilder:
    def __init__(self):
        self.root = None

    def create_root(self, name):
        self.root = XMLTag(name)

    def find_tag(self, current_tag, tag_name):
        if current_tag.name == tag_name:
            return current_tag
        for child in current_tag.children:
            found_tag = self.find_tag(child, tag_name)
            if found_tag:
                return found_tag
        return None

    def edit_tag(self, tag_name):
        if not self.root:
            print("Root tag is not set.")
            return

        tag = self.find_tag(self.root, tag_name)
        if not tag:
            print(f"Tag {tag_name} does not exist.")
            return

        while True:
            print(f"Editing tag: {tag_name}")
            print("1. Add attribute")
            print("2. Add child tag")
            print("3. Change tag value")
            print("4. Change attribute value")
            print("5. Exit")

            choice = input("Choose an option: ")

            if choice == "1":
                key = input("Enter attribute name: ")
                value = input("Enter attribute value: ")
                tag.add_attribute(key, value)
            elif choice == "2":
                child_name = input("Enter child tag name: ")
                child_value = input("Enter child tag value (leave empty if none): ")
                child_tag = XMLTag(child_name, child_value, tag)
                tag.add_child(child_tag)
            elif choice == "3":
                new_value = input("Enter new tag value: ")
                tag.set_value(new_value)
            elif choice == "4":
                attr_key = input("Enter attribute name to edit: ")
                if attr_key in tag.attributes:
                    attr_value = input("Enter new attribute value: ")
                    tag.set_attribute(attr_key, attr_value)
                else:
                    print(f"Attribute {attr_key} does not exist.")
            elif choice == "5":
                break
            else:
                print("Invalid choice. Please try again.")

    def print_xml(self):
        if not self.root:
            print("Root tag is not set.")
            return
        print(self.root.to_string())

    def save_to_file(self, filename):
        if not self.root:
            print("Root tag is not set.")
            return

        root_element = self.root.to_element()
        self.indent(root_element)
        tree = ET.ElementTree(root_element)
        tree.write(filename, encoding='utf-8', xml_declaration=True)

    def indent(self, elem, level=0):
        i = "\n" + level * "\t"
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "\t"
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                self.indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    def print_child_parent_relationship(self, current_tag=None, depth=0):
        if current_tag is None:
            current_tag = self.root

        parent_name = current_tag.parent.name if current_tag.parent else "-"
        children_names = [child.name for child in current_tag.children] if current_tag.children else ["-"]
        children_names_str = ", ".join(children_names)

        print(f"{current_tag.name}: Parent={parent_name}, Children={children_names_str}")

        for child in current_tag.children:
            self.print_child_parent_relationship(child, depth + 1)

    def load_from_file(self, filename):
        tree = ET.parse(filename)
        root = tree.getroot()
        self.root = self._element_to_tag(root)

    def _element_to_tag(self, element, parent=None):
        tag = XMLTag(element.tag, element.text.strip() if element.text else "", parent)
        for key, value in element.attrib.items():
            tag.add_attribute(key, value)
        for child in element:
            child_tag = self._element_to_tag(child, tag)
            tag.add_child(child_tag)
        return tag

# Example usage
if __name__ == "__main__":
    builder = XMLBuilder()

    while True:
        print("1. Create new XML")
        print("2. Load XML from file")
        print("3. Exit")

        choice = input("Choose an option: ")

        if choice == "1":
            builder.create_root("root")
        elif choice == "2":
            filename = input("Enter XML filename to load: ")
            builder.load_from_file(filename)
        elif choice == "3":
            break
        else:
            print("Invalid choice. Please try again.")

    while True:
        print("1. Edit tag")
        print("2. Print XML")
        print("3. Save XML to file")
        print("4. Print child-parent relationships")
        print("5. Exit")

        choice = input("Choose an option: ")

        if choice == "1":
            tag_name = input("Enter tag name to edit (or 'root' to edit root): ")
            builder.edit_tag(tag_name)
        elif choice == "2":
            builder.print_xml()
        elif choice == "3":
            filename = input("Enter filename to save XML: ")
            builder.save_to_file(filename)
        elif choice == "4":
            builder.print_child_parent_relationship()
        elif choice == "5":
            break
        else:
            print("Invalid choice. Please try again.")
import xml.etree.ElementTree as ET

class XMLTag:
    def __init__(self, name, value="", parent=None):
        self.name = name
        self.value = value
        self.attributes = {}
        self.children = []
        self.parent = parent

    def add_attribute(self, key, value):
        self.attributes[key] = value

    def add_child(self, child):
        child.parent = self
        self.children.append(child)

    def set_value(self, value):
        self.value = value

    def set_attribute(self, key, value):
        if key in self.attributes:
            self.attributes[key] = value
        else:
            print(f"Attribute {key} does not exist.")

    def to_string(self, depth=0):
        indent = "\t" * depth
        attr_str = " ".join([f'{key}="{value}"' for key, value in self.attributes.items()])
        if self.children:
            children_str = "\n".join([child.to_string(depth + 1) for child in self.children])
            return f"{indent}<{self.name} {attr_str}>{self.value}\n{children_str}\n{indent}</{self.name}>"
        else:
            if self.value:
                return f"{indent}<{self.name} {attr_str}>{self.value}</{self.name}>"
            else:
                if self.name == "root":
                    return f"{indent}<{self.name}></{self.name}>"
                return f"{indent}<{self.name} {attr_str.strip()}/>"  # Strip any extra spaces

    def to_element(self):
        element = ET.Element(self.name, self.attributes)
        if self.value:
            element.text = self.value
        for child in self.children:
            element.append(child.to_element())
        return element

class XMLBuilder:
    def __init__(self):
        self.root = None

    def create_root(self, name):
        self.root = XMLTag(name)

    def find_tag(self, current_tag, tag_name):
        if current_tag.name == tag_name:
            return current_tag
        for child in current_tag.children:
            found_tag = self.find_tag(child, tag_name)
            if found_tag:
                return found_tag
        return None

    def edit_tag(self, tag_name):
        if not self.root:
            print("Root tag is not set.")
            return

        tag = self.find_tag(self.root, tag_name)
        if not tag:
            print(f"Tag {tag_name} does not exist.")
            return

        while True:
            print(f"Editing tag: {tag_name}")
            print("1. Add attribute")
            print("2. Add child tag")
            print("3. Change tag value")
            print("4. Change attribute value")
            print("5. Exit")

            choice = input("Choose an option: ")

            if choice == "1":
                key = input("Enter attribute name: ")
                value = input("Enter attribute value: ")
                tag.add_attribute(key, value)
            elif choice == "2":
                child_name = input("Enter child tag name: ")
                child_value = input("Enter child tag value (leave empty if none): ")
                child_tag = XMLTag(child_name, child_value, tag)
                tag.add_child(child_tag)
            elif choice == "3":
                new_value = input("Enter new tag value: ")
                tag.set_value(new_value)
            elif choice == "4":
                attr_key = input("Enter attribute name to edit: ")
                if attr_key in tag.attributes:
                    attr_value = input("Enter new attribute value: ")
                    tag.set_attribute(attr_key, attr_value)
                else:
                    print(f"Attribute {attr_key} does not exist.")
            elif choice == "5":
                break
            else:
                print("Invalid choice. Please try again.")

    def print_xml(self):
        if not self.root:
            print("Root tag is not set.")
            return
        print(self.root.to_string())

    def save_to_file(self, filename):
        if not self.root:
            print("Root tag is not set.")
            return

        root_element = self.root.to_element()
        self.indent(root_element)
        tree = ET.ElementTree(root_element)
        tree.write(filename, encoding='utf-8', xml_declaration=True)

    def indent(self, elem, level=0):
        i = "\n" + level * "\t"
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "\t"
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                self.indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    def print_child_parent_relationship(self, current_tag=None, depth=0):
        if current_tag is None:
            current_tag = self.root

        parent_name = current_tag.parent.name if current_tag.parent else "-"
        children_names = [child.name for child in current_tag.children] if current_tag.children else ["-"]
        children_names_str = ", ".join(children_names)

        print(f"{current_tag.name}: Parent={parent_name}, Children={children_names_str}")

        for child in current_tag.children:
            self.print_child_parent_relationship(child, depth + 1)

# Example usage
if __name__ == "__main__":
    builder = XMLBuilder()
    builder.create_root("root")

    while True:
        print("1. Edit tag")
        print("2. Print XML")
        print("3. Save XML to file")
        print("4. Print child-parent relationships")
        print("5. Exit")

        choice = input("Choose an option: ")

        if choice == "1":
            tag_name = input("Enter tag name to edit (or 'root' to edit root): ")
            builder.edit_tag(tag_name)
        elif choice == "2":
            builder.print_xml()
        elif choice == "3":
            builder.save_to_file("makeXmlMap_output.xml")
        elif choice == "4":
            builder.print_child_parent_relationship()
        elif choice == "5":
            break
        else:
            print("Invalid choice. Please try again.")
import xml.etree.ElementTree as ET

class XMLTag:
    def __init__(self, name, value=""):
        self.name = name
        self.value = value
        self.attributes = {}
        self.children = []

    def add_attribute(self, key, value):
        self.attributes[key] = value

    def add_child(self, child):
        self.children.append(child)

    def set_value(self, value):
        self.value = value

    def set_attribute(self, key, value):
        if key in self.attributes:
            self.attributes[key] = value
        else:
            print(f"Attribute {key} does not exist.")

    def to_string(self, depth=0):
        indent = "\t" * depth
        attr_str = " ".join([f'{key}="{value}"' for key, value in self.attributes.items()])
        if self.children:
            children_str = "\n".join([child.to_string(depth + 1) for child in self.children])
            return f"{indent}<{self.name} {attr_str}>{self.value}\n{children_str}\n{indent}</{self.name}>"
        else:
            if self.value:
                return f"{indent}<{self.name} {attr_str}>{self.value}</{self.name}>"
            else:
                if self.name == "root":
                    return f"{indent}<{self.name}></{self.name}>"
                return f"{indent}<{self.name} {attr_str.strip()}/>"  # Strip any extra spaces

    def to_element(self):
        element = ET.Element(self.name, self.attributes)
        if self.value:
            element.text = self.value
        for child in self.children:
            element.append(child.to_element())
        return element

class XMLBuilder:
    def __init__(self):
        self.root = None

    def create_root(self, name):
        self.root = XMLTag(name)

    def find_tag(self, current_tag, tag_name):
        if current_tag.name == tag_name:
            return current_tag
        for child in current_tag.children:
            found_tag = self.find_tag(child, tag_name)
            if found_tag:
                return found_tag
        return None

    def edit_tag(self, tag_name):
        if not self.root:
            print("Root tag is not set.")
            return

        tag = self.find_tag(self.root, tag_name)
        if not tag:
            print(f"Tag {tag_name} does not exist.")
            return

        while True:
            print(f"Editing tag: {tag_name}")
            print("1. Add attribute")
            print("2. Add child tag")
            print("3. Change tag value")
            print("4. Change attribute value")
            print("5. Exit")

            choice = input("Choose an option: ")

            if choice == "1":
                key = input("Enter attribute name: ")
                value = input("Enter attribute value: ")
                tag.add_attribute(key, value)
            elif choice == "2":
                child_name = input("Enter child tag name: ")
                child_value = input("Enter child tag value (leave empty if none): ")
                child_tag = XMLTag(child_name, child_value)
                tag.add_child(child_tag)
            elif choice == "3":
                new_value = input("Enter new tag value: ")
                tag.set_value(new_value)
            elif choice == "4":
                attr_key = input("Enter attribute name to edit: ")
                if attr_key in tag.attributes:
                    attr_value = input("Enter new attribute value: ")
                    tag.set_attribute(attr_key, attr_value)
                else:
                    print(f"Attribute {attr_key} does not exist.")
            elif choice == "5":
                break
            else:
                print("Invalid choice. Please try again.")

    def print_xml(self):
        if not self.root:
            print("Root tag is not set.")
            return
        print(self.root.to_string())

    def save_to_file(self, filename):
        if not self.root:
            print("Root tag is not set.")
            return

        root_element = self.root.to_element()
        self.indent(root_element)
        tree = ET.ElementTree(root_element)
        tree.write(filename, encoding='utf-8', xml_declaration=True)

    def indent(self, elem, level=0):
        i = "\n" + level * "\t"
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "\t"
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                self.indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

# Example usage
if __name__ == "__main__":
    builder = XMLBuilder()
    builder.create_root("root")

    while True:
        print("1. Edit tag")
        print("2. Print XML")
        print("3. Save XML to file")
        print("4. Exit")

        choice = input("Choose an option: ")

        if choice == "1":
            tag_name = input("Enter tag name to edit (or 'root' to edit root): ")
            builder.edit_tag(tag_name)
        elif choice == "2":
            builder.print_xml()
        elif choice == "3":
            builder.save_to_file("makeXmlMap_output.xml")
        elif choice == "4":
            break
        else:
            print("Invalid choice. Please try again.")

 

'코딩 농장' 카테고리의 다른 글

Git1, Git2-CLI 버전관리  (0) 2022.06.26
GitHub 기본 명령어  (0) 2021.10.02