Implementing and Operating Cisco Enterprise Network Core Technologies (ENCOR) v1.2AutomationMedium
A network engineer is using a Python script to interact with a network device. The device's API returns data in XML format. The engineer needs to extract the value of the 'name' attribute from an XML element like `<interface name="GigabitEthernet1">`. Which Python library and method would be most suitable for this task?
- Are.search()
- Byaml.safe_load()
- Cxml.etree.ElementTree.fromstring().get()
- Djson.loads()
Show answer & explanationAnswer & explanation
Correct answer: C. xml.etree.ElementTree.fromstring().get()
The `xml.etree.ElementTree` module is the standard Python library for parsing XML. `fromstring()` parses an XML string into an ElementTree object, and the `.get()` method on an element object is used to retrieve the value of a specific attribute, such as 'name'.
Why the other options are wrong
- A. `re.search()` is for regular expressions and while it *could* parse XML, it's not the idiomatic or robust way to handle structured XML data.
- B. `yaml.safe_load()` is used for parsing YAML data, not XML.
- D. `json.loads()` is used for parsing JSON data, not XML.
Python xml.etree.ElementTree
The `xml.etree.ElementTree` module provides a simple and efficient API for parsing and creating XML data. It represents XML as a tree structure, allowing navigation and manipulation of elements and attributes.
- Standard Python library for XML.
- `fromstring()` parses XML text into an Element object.
- Elements have attributes accessible via the `.get()` method.
- Supports XPath-like expressions for finding elements.
Memory trick: XML is a tree, ElementTree helps you climb it and GET attributes.