2019年4月8日月曜日

lxml Cheetsheet

最近はlxmlをよく使ってXMLのパースをしていたのでチートシートを作りました。 既に色々なチートシートがあるので、自分の使いやすさだけ重視してます。

from lxml import etree

# I/O
tree = etree.fromstring('<xml>...</xml>')
parser = etree.XMLParser(remove_blank_text=True)  # many options
tree = etree.XML('<xml>...</xml>', parser)
tree = etree.parse('test.xml')
root = tree.getroot()
print(etree.tostring(root), pretty_print=True)  # many options

# search
node = tree.xpath('a')     # [<Element>]
node = tree.find('a')      #  <Element>  faster than xpath
node = tree.findall('a')   # [<Element>]
node = tree.iterfind('a')  # [<Element>]

# search node/attr/text
node = tree.xpath('description')
attr = node.attrib['about']
text = node.text

# search node/attr with namespaces
rdfNamespace = { 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' }
xlinkNamespace = { 'xlink': 'http://www.w3.org/1999/xlink' }
node = tree.xpath('rdf:description', namespaces=rdfNamespace)
href = node.xpath('@xlink:href', namespaces=xlinkNamespace)[0]

# iteration, sibling, etc.
for node in root.iter('node'):
  print(node)
node = node.getprevious().getnext().getparent()

# edit
title = etree.Element("title", href="https://lxml.de/tutorial.html")
root.append(title)
etree.SubElement(root, 'child')  #=> <root><child/></root>
etree.SubElement(xhtml, "{http://www.w3.org/1999/xhtml}body")
node.getparent().remove(node)
複雑な事をしようとしなければ、かなりあっさりした仕様なのは良いところ。 編集操作はもっと色々な機能があるみたいですが、あまり使ってないのであっさりにしときました。 その他の機能は公式のチュートリアルを参照。

0 件のコメント: