python将xml元素值提取到csv

python将xml元素值提取到csv,python,xml,Python,Xml,我是python新手,所以请耐心听我解释我要做的事情 这是我的xml <?xml version="1.0"?> <playlist> <list> <txdate>2015-10-30</txdate> <channel>cake</channel> <name>Play List</name> </list>

我是python新手,所以请耐心听我解释我要做的事情

这是我的xml

<?xml version="1.0"?>
<playlist>
    <list>
        <txdate>2015-10-30</txdate>
        <channel>cake</channel>
        <name>Play List</name>
    </list>
    <eventlist>
        <event type="MEDIA">
            <title>title1</title>
            <starttype>FIX</starttype>
            <mediaid>a</mediaid>
            <onairtime>2015-10-30T13:30:00:00</onairtime>
            <som>00:00:40:03</som>
            <duration>01:15:47:15</duration>
            <reconcilekey>123</reconcilekey>
            <category>PROGRAM</category>
            <subtitles>
                <cap>CLOSED</cap>
                <file>a</file>
                <lang>ENG</lang>
                <lang>GER</lang>
            </subtitles>
        </event>
        <event type="MEDIA">
            <title>THREE DAYS AND A CHILD</title>
            <mediaid>b</mediaid>
            <onairtime>2015-10-30T14:45:47:15</onairtime>
            <som>00:00:00:00</som>
            <duration>01:19:41:07</duration>
            <reconcilekey>321</reconcilekey>
            <category>PROGRAM</category>
            <subtitles>
                <cap>CLOSED</cap>
                <file>b</file>
                <lang>ENG</lang>
                <lang>GER</lang>
            </subtitles>
        </event>
    </eventlist>
</playlist>
我在其他一些非标准库中尝试了这一点,但对于您的要求(如评论中所述),我并没有取得多大成功-

只需每个

您应该使用ElementTree的
findall()
方法,使用
type=“MEDIA”
获取所有
事件
元素,然后从中获取子
mediaid
元素。范例-

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
with open('new.csv','w') as outfile:
    for elem in root.findall('.//event[@type="MEDIA"]'):
            mediaidelem = elem.find('./mediaid')
            if mediaidelem is not None:
                    outfile.write("{}\n".format(mediaidelem.text))
根据您的要求(如评论中所述)-

只需每个

您应该使用ElementTree的
findall()
方法,使用
type=“MEDIA”
获取所有
事件
元素,然后从中获取子
mediaid
元素。范例-

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
with open('new.csv','w') as outfile:
    for elem in root.findall('.//event[@type="MEDIA"]'):
            mediaidelem = elem.find('./mediaid')
            if mediaidelem is not None:
                    outfile.write("{}\n".format(mediaidelem.text))

那么,您希望在文件中输出什么呢?对于上面的示例xml,第一行是“a”,第二行是“b”,所以您只需要文件中的所有
mediad
值?没有任何条件,对吗?是的,只是每个
中的
媒体ID
,那么您希望在文件中输出什么?对于上面的示例xml,第一行是“a”,第二行是“b”,所以您只需要文件中的所有
mediad
值?没有任何条件,对吗?是的,只是每个