Module for working with XML files

What do we do



Today we will create a module for working with XML files .



What for



Sometimes, when developing a program in Python, you need to make settings that any user can change without changing the code.



What do we need



  • Knowledge of Java programming Python
  • Python3
  • Python xml library


Let's start



First, let's import the library and create the main class.



import xml.etree.ElementTree as xml

class XML:
    pass


To work with an XML file, we need the XML file itself, but on the first launch of the program, the user may not have this file, so we need to create it.



When creating an instance of the class, pass the file name and save it to the fileName parameter.



import xml.etree.ElementTree as xml

class XML:
    fileName:str

    def __init__(self, fileName):
        self.fileName = fileName + ".xml"


Now we will write a function that will check if our file exists and will call it at the time of creating an instance of the class.



import xml.etree.ElementTree as xml

class XML:
    fileName:str

    def __init__(self, fileName):
        self.fileName = fileName + ".xml"
        self.openFile()

    def openFile(self):
        try:
            file = open(self.fileName, "r")
        except FileNotFoundError:
            print("File not found")


Next, we will write a function that will create our file if it does not exist, and we will call it if the program does not find the file.



class XML:
    fileName:str

    def __init__(self, fileName):
        self.fileName = fileName + ".xml"
        self.openFile()

    def openFile(self):
        try:
            file = open(self.fileName, "r")
        except FileNotFoundError:
            self.createFile()

    def createFile(self):
        rootXML = xml.Element("settings")

        text = xml.Element("text")
        text.text = "Text"
        rootXML.append(text)

        file = open(self.fileName, "w")
        file.write(xml.tostring(rootXML, encoding="utf-8", method="xml").decode(encoding="utf-8"))
        file.close()


Now let's take a closer look at the XML.createFile () function:



  • rootXML is the main element that will allow writing all the settings to a new file much faster than if we wrote all the tags separately
  • text is the tag that will be displayed inside rootXML. In the Element.text field, specify what should be inside the element


To make a list of items, for example:



<settings>
    <text>Hello, world!</text>
    <list>
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </list>
</settings>


Create a main element, in our case "list" and sub-elements "item".



list = xml.Element("list")
rootXML.append(list)

item: xml.SubElement

item = xml.SubElement(list, "item")
item.text = "1"

item = xml.SubElement(list, "item")
item.text = "2"

item = xml.SubElement(list, "item")
item.text = "3"

#xml.SubElement(parent: xml.Element or xml.SubElement, tag: str)
#     


If our program is a program with an interface, and the settings file is used to store any values ​​that the user can change, then we need a function that can change the value of an element. Let's write it.



class XML:
    fileName:str

    def __init__(self, fileName):
        self.fileName = fileName + ".xml"
        self.openFile()

    def openFile(self):
        try:
            file = open(self.fileName, "r")
        except FileNotFoundError:
            self.createFile()

    def createFile(self):
        rootXML = xml.Element("settings")

        text = xml.Element("text")
        text.text = "Text"
        rootXML.append(text)

        file = open(self.fileName, "w")
        file.write(xml.tostring(rootXML, encoding="utf-8", method="xml").decode(encoding="utf-8"))
        file.close()

    def editFile(self, element, value):
        tree = xml.ElementTree(file=self.fileName)
        rootXML = tree.getroot()
        for elem in rootXML.iter(element):
            elem.text = str(value)

        tree = xml.ElementTree(rootXML)
        tree.write(self.fileName)


In the editFile () function, we pass the name of the element (element) that we want to change and the new value (value).



And the last thing you need for any work with XML files is data parsing.



class XML:
    fileName:str

    def __init__(self, fileName):
        self.fileName = fileName + ".xml"
        self.openFile()

    def openFile(self):
        try:
            file = open(self.fileName, "r")
        except FileNotFoundError:
            self.createFile()

    def createFile(self):
        rootXML = xml.Element("settings")

        text = xml.Element("text")
        text.text = "Text"
        rootXML.append(text)

        file = open(self.fileName, "w")
        file.write(xml.tostring(rootXML, encoding="utf-8", method="xml").decode(encoding="utf-8"))
        file.close()

    def editFile(self, element, value):
        tree = xml.ElementTree(file=self.fileName)
        rootXML = tree.getroot()
        for elem in rootXML.iter(element):
            elem.text = str(value)

        tree = xml.ElementTree(rootXML)
        tree.write(self.fileName)

    def parsingFile(self, elements, text = True):
        tree = xml.ElementTree(file=self.fileName)
        rootXML = tree.getroot()
        for element in rootXML.iter(elements):
            if (text):
                return element.text
            return element


In the parsingFile () method, we pass the name of the tag (element) that we want to receive and the boolean value of which data type to return. If text = True then the value of the element will be returned, otherwise the object, which can then be iterated over. For example, we have an XML file:



<settings>
    <text>Hello, world!</text>
    <list>
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </list>
</settings>


And if we want to display all the item values ​​to the console, then we parse the "list" parameter and pass False in the 2nd parameter to parsingFile (). We begin to iterate over the received element and display element.text - having the value of the selected element.



import XML as xml

moduleXml = xml.XML("settings")

for element in moduleXml.parsingFile("list", False):
    print(element.text)


After executing this code in the console, we will see:



1
2
3


Conclusion



As a result, we got a module that you can use in your projects to work with XML files.



Project on gitHub



Thank you all and good luck.



All Articles