Python: lxml

(Last Updated On: )

This post focus’ on the lxml package.

First you need to install the package

  1. from lxml import etree

Create xml object by string

  1. xml_str = "<root><subitem attr='test'>rec</subitem></root>"
  2. root = etree.fromstring(xml_str)

Get text in node

  1. text_str = root.xpath('//root/subitem/text()')[0]

Get Attribute

  1. attr = root.xpath('//root/subitem')[0].attrib['attr']