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, "another").text = "child 3"
print('遍歷所有節點,包括entity和comment')
print(etree.tostring(root, pretty_print=true))
print('\n')
print('遍歷所有節點')
for element in root.iter():
print("%s - %s" % (element.tag, element.text))
print('\n')
print('遍歷所有child節點')
for element in root.iter("child"):
print("%s - %s" % (element.tag, element.text))
print('\n')
print('遍歷所有child節點和another節點')
for element in root.iter("another", "child"):
print("%s - %s" % (element.tag, element.text))
print('\n')
print('遍歷所有節點,包括entity和comment')
for element in root.iter():
if isinstance(element.tag, str): # or 'str' in python 3
print("%s - %s" % (element.tag, element.text))
else:
print("special: %s - %s" % (element, element.text))
print('\n')
print('遍歷所有節點')
for element in root.iter(tag=etree.element):
print("%s - %s" % (element.tag, element.text))
print('\n')
print('遍歷所有entity')
for element in root.iter(tag=etree.entity):
print(element.text)
print('\n')
輸出:
遍歷所有節點,包括entity和comment
b'child 1
child 2
child 3ê\n'
遍歷所有節點
root - none
child - child 1
child - child 2
another - child 3
- ê- some comment
遍歷所有child節點
child - child 1
child - child 2
遍歷所有child節點和another節點
child - child 1
child - child 2
another - child 3
遍歷所有節點,包括entity和comment
root - none
child - child 1
child - child 2
another - child 3
special: ê - ê
special: - some comment
遍歷所有節點
root - none
child - child 1
child - child 2
another - child 3
遍歷所有entity
ê
節點List相關操作
為方便遍歷子節點,lxml將節點list的操作盡可能的與python處理list的方式一樣保持一致 建立xml from lxml import etree root etree.element root 建立根節點 child1 建立子節點child1 child2 etree.subelemen...
節點文字相關操作
對於許多xml檔案,乙個根節點向下會有很多層級的子節點,通常會把文字放置到最最底層的節點 因此要想訪問文字,就必須要訪問最底層的那個節點 但也有一些xml檔案,text會放置到中間層級的節點中,比如html 建立帶文字節點 root etree.element root root.text text...
jQuery之dom操作 遍歷節點
jquery之dom操作 遍歷節點 children children selector 只考慮子元素,不考慮其他後代元素 next next selector 下乙個兄弟節點 prev prev selector 上乙個兄弟節點 siblings siblings selector 其他兄弟節點 ...