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>
3

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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())

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.