我非常非常新的python world .im有一个新的要求,我需要在python中打印节点值和节点名。但是我得到一些错误。 任何人都可以帮助我...... !!!!
这是我的样本xml:
<task chapnbr="05" sectnbr="41" subjnbr="05" func="210" seq="8" pgblknbr="2" chg="N" key="4B5014E906" revdate="20051230">
<effect effrg="801899" efftext="ZAP ALL" />
<title>WING</title>
<refblock>(<grphcref refid=NAX00000>Figure 208</grphcref>)</refblock>
<tfmatr>
<pretopic>
<title>General</title>
<list1>
<l1item>
<para>This procedure is a scheduled maintenance task.</para>
</l1item>
</list1>
</pretopic>
</tfmatr>
<topic>
<title>Zonal Inspection</title>
<subtask chapnbr="05" sectnbr="41" subjnbr="05" func="210" seq="008" pgblknbr="2" chg="N" key="B7A276D9D" revdate="20051230">
<effect effrg="8018" efftext="ZAP ALL" />
<list1>
<l1item>
<para>Do the zonal inspection.</para>
</l1item>
</list1>
</subtask>
</topic>
<graphic chapnbr="05" sectnbr="41" subjnbr="05" func="990" seq="808" pgblknbr="2" chg="N" key=NAX00000 revdate="20051230">
<effect effrg="801899" efftext="ZAP ALL" />
<title>Figure 208. Leading Edge to Front Spar (Outboard of Nacelle Strut) Left Wing - General Visual (External)</title>
<sheet gnbr="811DE0C" sheetnbr="1" chg="N" key="5C152" revdate="20051230">
<effect effrg="801899" efftext="ZAP ALL" />
</sheet>
</graphic>
</task>
我的示例python代码:
import os
import sys
import xml.etree.ElementTree as ET
directory=raw_input("Enter the folderPath : ")
files=raw_input("Enter the File type : ")
def select_files_in_folder(dir, ext):
for file in os.listdir(dir):
if file.endswith('.%s' % ext):
yield os.path.join(dir, file)
def print_node(root):
if root.childNodes[0]:
for node in root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
print node.tagName,"has value:", node.nodeValue, "and is child of:", node.parentNode.tagName
print_node(node)
for file in select_files_in_folder(directory, files):
tree = ET.parse(file)
root = tree.getroot()
print_node(root)
我低于错误。
答案 0 :(得分:0)
您收到 AttributeError ,因为 xml.etree.ElementTree.Element 对象没有属性 childNodes 。
要迭代childern元素,只需for child in elem
。
def print_node(root):
for node in root:
if node.nodeType == node.ELEMENT_NODE:
print node.tagName,"has value:", node.nodeValue, "and is child of:", node.parentNode.tagName
print_node(node)