Reputation: 836
I am trying to grab the attributes from an XML tag so I can get the correct data and place it in a CSV file
I have attempted to find some answers, but have found nothing definitive other than how to grab that tag itself, or get the attributes using another language.
Here is what a line from the XML file will look like:
<item id="16" class="ItemClass" status="closed"
opened="2008-07-14T22:31:10Z" closed="2008-07-14T23:45:08Z"
url="www.google.com"/>
The Tag is "item" The attributes are "id", "class", "status", "opened", "closed", "url"
I can get the tag name, and the items inside the tag (<tag>item inside tag</tag>)
using a method found here:
import xml.etree.ElementTree as ET
import csv
item_head = []
item = []
[...]
name = item.find('item').tag
item_head.append(name)
name = item.find('item').text
item.append(name)
But I want to get that ATTRIBUTES, not the tag.
I can easily write the header of the file since the items will always contain the same information. So, this would look like:
item_head.append('id')
item_head.append('class')
item_head.append('status')
...and so on...
But I don't know how to grab the other information, such as id="16"
End result should be something like this:
id, class, status, opened, closed, url
16, ItemClass, closed, 2008-07-14T22:31:10Z, 2008-07-14T23:45:08Z, www.google.com
Can anyone help me with this?
Upvotes: 0
Views: 491
Reputation: 1191
An xml.etree.ElementTree.Element also has an attrib
property, which is a dictionary containing the element’s attributes
>>> item.attrib['id']
'16'
Upvotes: 2