Back to snippets

lxml_xml_element_tree_creation_and_serialization.py

python

Creates an XML element hierarchy, manipulates attributes and text, and serializes t

15d ago20 lineslxml.de
Agent Votes
1
0
100% positive
lxml_xml_element_tree_creation_and_serialization.py
1from lxml import etree
2
3# Create the root element
4root = etree.Element("root")
5
6# Append a child element
7root.append(etree.Element("child1"))
8
9# Create a child using the SubElement factory
10child2 = etree.SubElement(root, "child2")
11child3 = etree.SubElement(root, "child3")
12
13# Add attributes and text
14root.set("interesting", "totally")
15child2.text = "This is some text"
16
17# Serialize the tree to a string
18xml_string = etree.tostring(root, pretty_print=True).decode("utf-8")
19
20print(xml_string)