Diferències

Ací es mostren les diferències entre la revisió seleccionada i la versió actual de la pàgina.

Enllaç a la visualització de la comparació

info:cursos:pue:python-pcpp1:m5:2.1 [04/03/2024 11:34] – creat mateinfo:cursos:pue:python-pcpp1:m5:2.1 [04/03/2024 11:37] (actual) mate
Línia 282: Línia 282:
  
 In the example above, we use the ''dump'' method, which allows us to debug either the whole tree or a single element. In the example above, we use the ''dump'' method, which allows us to debug either the whole tree or a single element.
 +
 +== Building an XML document (part 2)
 +In addition to the ''Element'' class, the ''xml.etree.ElementTree'' module offers a function for creating child elements called ''SubElement''. The ''SubElement'' function takes three arguments.
 +
 +The first one defines the parent element, the second one defines the tag name, and the third (optional) defines the attributes of the element. Let's see how it looks in action and analyze the code in the editor.
 +
 +<code python>import xml.etree.ElementTree as ET
 +
 +root = ET.Element('data')
 +movie_1 = ET.SubElement(root, 'movie', {'title': 'The Little Prince', 'rate': '5'})
 +movie_2 = ET.SubElement(root, 'movie', {'title': 'Hamlet', 'rate': '5'})
 +ET.dump(root)
 +</code>
 +
 +Result:
 +<code><data><movie rate="5" title="The Little Prince" /><movie rate="5" title="Hamlet" /></data></code>
 +
 +In the example, we've added two child elements called ''movie'' to the root element. The created elements are objects of the ''Element'' class, so we can use all of the methods that we learned about during this course.
 +
 +**NOTE**: To save a document using the write method, we need to have an ''ElementTree'' object. To do this, pass our root element to its constructor:
 +
 +<code python>tree = ET.ElementTree(root)</code>
  • info/cursos/pue/python-pcpp1/m5/2.1.1709548489.txt.gz
  • Darrera modificació: 06/07/2026 18:29
  • (edició externa)