0

I need to modify an xml file in python; specifically I need to add a new entry under the video tag. For instance, having something like this

<sources>
    <programs>
        <default pathversion="1"></default>
    </programs>
    <video>
        <default pathversion="1"></default>
        <source>
            <name>Dir 1</name>
            <path pathversion="1">/path/to/dir1/</path>
            <allowsharing>true</allowsharing>
        </source>
        <source>
            <name>Dir 2</name>
            <path pathversion="1">/path/to/dir2/</path>
            <allowsharing>true</allowsharing>
        </source>
    </video>
    <music>
        <default pathversion="1"></default>
    </music>
    <pictures>
        <default pathversion="1"></default>
    </pictures>
</sources>

I need to create a new entry under <video>...</video> as follows:

<source>
    <name>Dir 3</name>
    <path pathversion="1">/path/to/dir3/</path>
    <allowsharing>true</allowsharing>
</source>

and update the original xml file. What would be the best practice to do so?

2
  • 2
    You'll want to use an XML parser in most cases, but for very simple cases like this, where the structure of the documents is consistent and well-known, you can just do a text replacement... replace </video> with your new markup plus </video> Commented May 9, 2022 at 17:44
  • @kindall very interesting, thanks! It'd be nice to have this using xml.etree.ElementTree as well though. Thanks for your comment! Commented May 9, 2022 at 17:50

1 Answer 1

2

Using xml.etree.ElementTree to insert.

import xml.etree.ElementTree as ET

tree = ET.parse('sample.xml')

root = tree.getroot()
insertLoc = root.findall("./video")[0]
start1 = ET.Element(insertLoc)
insSource = ET.SubElement(start1, "source")
insName = ET.SubElement(insSource, "name")
insName.text = "Dir 3"
insPath = ET.SubElement(insSource, "path")
insPath.attrib = {'pathversion':"1"}
insPath.text = "/path/to/dir3/"
insAllow = ET.SubElement(insSource, "allowsharing")
insAllow.text="true"

insertLoc.append(insSource)

print(ET.dump(tree))
Sign up to request clarification or add additional context in comments.

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.