建立XMLpython
from lxml import etree root = etree.Element("root") #建立根節點 root.append(etree.Element("child1")) #建立子節點child1 child2 = etree.SubElement(root, "child2") #建立子節點child2 child3 = etree.SubElement(root, "child3") #建立子節點child3
具體的xml文件結構以下:
<root> <child1></child1> <child2></child2> <child3></child3> </root>
獲取當前節點指定索引處子節點app
child = root[0] print(child.tag) #輸出:child1
獲取當前節點子節點個數spa
print(len(root)) #輸出:3
獲取節點在父節點中的索引code
print(root.index(root[1])) #輸出:1
子節點遍歷xml
children = list(root) for child in children: print(child.tag)
#或
for child in root: print(child.tag)
子節點插入blog
root.insert(0, etree.Element("child0"))
節點List操做索引
start = root[:1] end = root[-1:] print(start[0].tag) #輸出:child0 print(end[0].tag) #輸出:child3
包含子節點判斷element
#不推薦: if root: print("The root element has children") #推薦: 該種方式更能讓人讀懂是用來判斷節點是否包含子節點的 if len(root): print("The root element has children")
父節點判斷get
print(root is root[0].getparent()) #輸出:True
相鄰節點判斷io
print(root[0] is root[1].getprevious()) #輸出:True print(root[1] is root[0].getnext()) #輸出:True
節點判斷
print(etree.iselement(root)) #輸出:True root11='' print(etree.iselement(root11)) #輸出:False,由於root11只是變量
子節點移動
for child in root: print(child.tag) '''輸出: child0 child1 child2 child3 ''' root[0] = root[-1] #child3是移動到了index爲0的位置,它覆蓋了child1
for child in root: print(child.tag) '''輸出: child3 child1 child2 '''
子節點拷貝
若是要將元素複製到lxml.etree中的其餘位置,請考慮使用python標準庫中的copy模塊建立一個獨立的深度複製
from lxml import etree from copy import deepcopy root = etree.Element("root") #建立根節點 root.append(etree.Element("child1")) #建立子節點child1 child2 = etree.SubElement(root, "child2") #建立子節點child2 child3 = etree.SubElement(root, "child3") #建立子節點child3 element = etree.Element("neu") element.append(deepcopy(root[1])) print(element[0].tag) #輸出:child2 print([ c.tag for c in root ]) #輸出:['child1', 'child2', 'child3'],原root節點下的子節點沒有變化 element01 = etree.Element("neu01") element01.append(root[1]) print(element01[0].tag) #輸出:child2 print([ c.tag for c in root ]) #輸出:['child1', 'child3'],原root節點下的子節點有變化,child2不見了