Reputation: 388
xml file:
<Protocol1 channel="AljazeeraHD">
<frame source="vd01" id="4">
</frame>
<frame id="18" source="vd01">
<rectangle id="1" height="87" width="976" y="889" x="414"/>
</frame>
<frame id="23" source="vd01">
<rectangle id="1" x="300" y="886" width="1095" height="89"/>
</frame>
<frame id="35" source="vd01">
<rectangle id="1" x="316" y="53" width="242" height="34"/>
<rectangle id="2" x="635" y="886" width="755" height="90"/>
</frame>
</Protocol1>
Want to access value of attribute 'x' from rectangle.
Code to convert xml_to _csv:
def xml_to_csv(path):
xml_list = []
for xml_file in glob.glob(path):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('frame'):
frameNo = root.attrib['channel']+'_'+member.attrib['source']+'_frame_'+member.attrib['id']
#print(member.find('rectangle').attrib['x'])
#print(member.getchildren().attrib['x'])
#print(member.find('rectangle').attrib['x'])
value = (frameNo,
1920,
1080,
'Artificial',
int(member.find('rectangle').attrib['x']),
)
xml_list.append(value)
print(glob.glob(path))
column_name = ['FrameNo', 'imgwidth', 'imgheight',
'class','X']
xml_df = pd.DataFrame(xml_list, columns=column_name)
print(xml_list)
return xml_df
Where 'member= frame' in a loop.
1.
member.getchildren().attrib['x']
AttributeError: 'NoneType' object has no attribute 'attrib'
2.
member.find('rectangle').attrib['x']
AttributeError: 'list' object has no attribute 'attrib'
Upvotes: 1
Views: 138
Reputation: 24930
Since you are using ElementTree and assuming your code looks like this:
members = """
<doc>
<frame id="18" source="vd01">
<rectangle id="1" height="87" width="976" y="889" x="414"/>
</frame>
<frame id="19" source="vd01">
<rectangle id="1" height="87" width="976" y="889" x="333"/>
</frame>
</doc>
"""
Then this should work:
import xml.etree.ElementTree as ET
doc = ET.fromstring(members)
for frame in doc.findall('.//frame'):
print(frame.attrib['x'])
Output:
414
333
EDIT:
Following your change to the xml, change the for
loop to:
for frame in doc.findall('.//frame[rectangle]'):
for rec in frame.findall('.//rectangle'):
print(rec.attrib['x'])
Now the output should be:
414
300
316
635
Upvotes: 1