節點遍歷相關操做

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"
root.append(etree.Entity("#234"))
root.append(etree.Comment("some comment"))

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')

輸出:app

遍歷全部節點,包括entity和comment
b'<root><child>Child 1</child><child>Child 2</child><another>Child 3</another>&#234;<!--some comment--></root>\n'


遍歷全部節點
root - None
child - Child 1
child - Child 2
another - Child 3
<cyfunction Entity at 0x00000229A2BA41B8> - &#234;
<cyfunction Comment at 0x00000229A2BA4048> - 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: &#234; - &#234;
SPECIAL: <!--some comment--> - some comment


遍歷全部節點
root - None
child - Child 1
child - Child 2
another - Child 3


遍歷全部entity
&#234;

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------spa

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------code

相關文章
相關標籤/搜索