節點List相關操作

2022-06-25 13:12:11 字數 3411 閱讀 8970

為方便遍歷子節點,lxml將節點list的操作盡可能的與python處理list的方式一樣保持一致

建立xml

from lxml import

etree

root = etree.element("

root

") #

建立根節點

child1

")) #

建立子節點child1

child2 = etree.subelement(root, "

child2

") #

建立子節點child2

child3 = etree.subelement(root, "

child3

") #

建立子節點child3

具體的xml檔案結構如下:

<

root

>

<

child1

>

child1

>

<

child2

>

child2

>

<

child3

>

child3

>

root

>

獲取當前節點指定索引處子節點

child =root[0]

print(child.tag) #

輸出:child1

獲取當前節點子節點個數

print(len(root)) #

輸出:3

獲取節點在父節點中的索引

print(root.index(root[1])) #

輸出:1

子節點遍歷

children =list(root)

for child in

children:

print

(child.tag)#或

for child in

root:

print(child.tag)

子節點插入

root.insert(0, etree.element("

child0

"))

節點list操作

start = root[:1]

end = root[-1:]

print(start[0].tag) #

輸出:child0

print(end[0].tag) #

輸出:child3

包含子節點判斷

#

不推薦:

ifroot:

print("

the root element has children")

#推薦: 該種方式更能讓人讀懂是用來判斷節點是否包含子節點的

iflen(root):

print("

the root element has children

")

父節點判斷

print(root is root[0].getparent())  #

輸出:true

相鄰節點判斷

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

") #

建立根節點

child1

")) #

建立子節點child1

child2 = etree.subelement(root, "

child2

") #

建立子節點child2

child3 = etree.subelement(root, "

child3

") #

建立子節點child3

element = etree.element("

neu"

)print(element[0].tag) #

輸出:child2

print([ c.tag for c in root ]) #

輸出:['child1', 'child2', 'child3'],原root節點下的子節點沒有變化

element01 = etree.element("

neu01")

print(element01[0].tag) #

輸出:child2

print([ c.tag for c in root ]) #

輸出:['child1', 'child3'],原root節點下的子節點有變化,child2不見了

節點遍歷相關操作

from lxml import etree root etree.element root etree.subelement root,child text child 1 etree.subelement root,child text child 2 etree.subelement root...

list列表相關操作

字串的操作 s alexwusir s1 s.capitalize print s1 大寫,小寫 s2 s.upper s3 s.lower print s2,s3 s str aceq your input input 請輸入驗證碼 不區分大小寫 if s str.lower your input...

節點文字相關操作

對於許多xml檔案,乙個根節點向下會有很多層級的子節點,通常會把文字放置到最最底層的節點 因此要想訪問文字,就必須要訪問最底層的那個節點 但也有一些xml檔案,text會放置到中間層級的節點中,比如html 建立帶文字節點 root etree.element root root.text text...