Lxml. etree tutorial 3: Elements carry attributes as a dict

Source: Internet
Author: User

XML elements support attributes. You can create them directly in the Element factory.

>>> root = etree.Element("root", interesting="totally")>>> etree.tostring(root)b'<root interesting="totally"/>'

Attribute is a name-Value Pair without sequence, so a convenient way to process them is through the element interface of the class dictionary.

>>> print(root.get("interesting"))totally>>> print(root.get("hello"))None>>> root.set("hello", "Huhu")>>> print(root.get("hello"))Huhu>>> etree.tostring(root)b'<root interesting="totally" hello="Huhu"/>'>>> sorted(root.keys())['hello', 'interesting']>>> for name, value in sorted(root.items()):...     print('%s = %r' % (name, value))hello = 'Huhu'interesting = 'totally'

In other cases, for example, you want to search for elements or access an object of a real dictionary class. You can use attrib attributes

>>> attributes = root.attrib>>> print(attributes["interesting"])totally>>> print(attributes.get("no-such-attribute"))None>>> attributes["hello"] = "Guten Tag">>> print(attributes["hello"])Guten Tag>>> print(root.get("hello"))Guten Tag

Note that attrib is a class dictionary object supported by the Element itself. This means that any change to Elements will be reflected to attrib, and vice versa. This also means that the XML tree remains in the memory as long as the attrib of one of Elements is in use. To obtain the attributes of an independent image, instead of relying on the XML tree, copy it to the dictionary.

>>> d = dict(root.attrib)>>> sorted(d.items())[('hello', 'Guten Tag'), ('interesting', 'totally')]

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.