Source: http://lxml.de/tutorial.html
Lxml is a very powerful library for processing XML in python, and it is very easy to parse and generate XML Files. The following content translates part of the link
1. Generating an empty XML node
from Import = Etree. Element ("root")print(etree.tostring (root, pretty_print=true))
< Root />
2. Generating XML child nodes
from lxml import Etreeroot = Etree. Element ( root " ) root.append (etree. Element ( child1 " = Etree. subelement (root, child2 " " #方法二child2 = Etree. subelement (root, child3 " " print (etree.tostring (root) )
< Root > < Child1 /> < child2 /> < child3 /> </ Root >
3. Generating an XML node with content
from Import = Etree. Element ("root""HelloWorld"print( Etree.tostring (root, Pretty_print=true))
< Root > Hello World</root>
4. Properties
Storing attributes as a dictionary in lxml
Build Properties
fromlxmlImportEtreeroot= Etree. Element ("Root", intersting ="Totally")#Method OneRoot.set ("Hello","Huhu")#Method TwoRoot.text ="Hello world"Print(etree.tostring (root))
<intersting= "totally" Hello= "huhu"> Hello World</root>
Get Properties
Method One:
Root.get ("interesting") root.get ("hello")
Totallyhuhu
Method Two:
attributes = root.attribprint(attributes["interesting"])
Traverse Properties
for inch sorted (root.items ()): Print ('%s =%r' % (name, value))
5. Generate Special Content
The following xml, the middle of the text is <br/> split, need to use. tail
< html >< body > Hello< br /> World</ body ></ html >
HTML = etree. Element ( html " ) body = Etree. subelement (html, body " ) body.text = text br = Etree. subelement (body, " " br . tail = " tail " etree.tostring (html)
6. Traverse
Traversing nodes
for inch root.iter (): Print ("%s-%s" % (element.tag, Element.text))
Iterates over the specified child node and writes the subsection name to ITER ()
for in Root.iter ("child"): print(" %s-%s" % (element.tag, Element.text))
7. Finding node content with XPath
Build_text_list = Etree. XPath ("//text ()"# lxml.etree only! Print (build_text_list (html))
8. Finding nodes
iterfind (): traverse all node matching expressions
findall (): Returns the list of nodes that satisfy the match
Find (): Returns the first one that satisfies the match
FindText (): Returns the First. text content that satisfies the match condition
Has the following XML content
root = Etree. XML ("<root><a x= ' 123 ' >aText<b/><c/><b/></a></root> ")
Find child nodes
Print (root.find ("b")) None Print (root.find ("a"). Tag) a
Find any node in the tree
Print (root.find (".//b"). Tag) b for in Root.iterfind (".//b") ['b' ' b ']
Finds the node with the specified attribute
Print (root.findall (".//a[@x]") [0].tag) a Print (root.findall (".//a[@y]")) []
9. String Parsing to XML
" <root>data</root> >>> root = etree.fromstring (some_xml_data)print(root.tag) root> >> etree.tostring (root) b'<root>data</root>'
10. Quickly generate XML and HTML using E-factory
>>> fromLxml.builderImportE>>>defCLASS (*args):#class is a reserved word in Python return{"class":' '. Join (args)}>>> HTML = page =(e.html (#Create an Element called "html"E.head (e.title ("This is a sample document")), e.body (e.h1 ("hello!", CLASS ("title")), E.P ("This was a paragraph with", e.b ("Bold"),"text in it!"), E.P ("this was another paragraph, with a","\ n", E.a ("Link", href="http://www.python.org"),"."), E.P ("Here is some reservered characters: <spam&egg>."), Etree. XML ("<p>and finally an embedded XHTML fragment.</p>"), ) ) )>>>Print(etree.tostring (page, pretty_print=True)) isA sample document</title> class="title">Hello! isA paragraph with <b>bold</b> textinchIt!</p> <p>this isanother paragraph, with a<a href="http://www.python.org">link</a>.</p> <p>here is some reservered characters: <spam&egg>. </p> <p>andfinallyAn embedded XHTML fragment.</p> </body>
"python" lxml