parse data using objectify.fromstring in python

To parse data using objectify.fromstring in Python, follow these steps:

  1. Import the required libraries:
main.py
from lxml import etree
from io import StringIO
from lxml import objectify
74 chars
4 lines
  1. Create an XML string to be parsed:
main.py
xml_string = '<root><user><name>John</name><age>28</age></user></root>'
72 chars
2 lines
  1. Parse the XML string using objectify.fromstring() method:
main.py
root = objectify.fromstring(xml_string)
40 chars
2 lines
  1. Access the data using objectify object:
main.py
print(root.user.name)
print(root.user.age)
43 chars
3 lines

Output:

main.py
John
28
8 chars
3 lines

Here is the complete program:

main.py
from lxml import etree
from io import StringIO
from lxml import objectify

xml_string = '<root><user><name>John</name><age>28</age></user></root>'
root = objectify.fromstring(xml_string)

print(root.user.name)
print(root.user.age)
231 chars
10 lines

Output:

main.py
John
28
8 chars
3 lines

gistlibby LogSnag