0

I have a simple problem that, i want to update/modify the content of an xml node using python. I am using python 3.6 version.

I want to write a python script that, will modify the status node content to "On" and directoryName node to "Users/

 <main>
        <status>off</status>

        <directoryName>nothing</directoryName>

 </main>
  • Possible duplicate of [Creating a simple XML file using python](https://stackoverflow.com/questions/3605680/creating-a-simple-xml-file-using-python) – grooveplex Feb 17 '19 at 12:35
  • Not a duplicate but similar question : https://stackoverflow.com/q/8236107/1513933 – Laurent LAPORTE Feb 17 '19 at 13:34
  • Possible duplicate of [Find and Replace Values in XML using Python](https://stackoverflow.com/questions/6523886/find-and-replace-values-in-xml-using-python) – Laurent LAPORTE Feb 17 '19 at 13:36

3 Answers3

0

I got the answer. I forgot to write at the end

 xmlHandler = "System_Settings/System_controller.xml"

    xmlDom=ElementTree.parse(xmlHandler)

    xmlDom.find("status").text = "on"
    print(xmlDom.find("status").text)

    xmlDom.write(xmlHandler)
0

If you can afford to install an additional package, take a look at BeautifulSoup. It makes parsing html and xml quite simple.

import bs4
xml = """
<main>
    <status>off</status>
    <directoryName>nothing</directoryName>
</main>"""
soup = bs4.BeautifulSoup(xml, "xml")
soup.status.string="on"
print(soup.prettify())
Uwe Brandt
  • 341
  • 2
  • 8
0

Using lxml library (which is also used by BeautifulSoup):

from lxml import etree

node = etree.XML("""
<main>
    <status>off</status>
    <directoryName>nothing</directoryName>
</main>""")
status = "On"

status_node = node.xpath("/main/status")[0]
status_node.text = status

Then with print(etree.tounicode(node)), you get:

<main>
    <status>On</status>
    <directoryName>nothing</directoryName>
</main>
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103