python读取xml中的字段值

import xml.etree.ElementTree as ET
xml_string = '''<?xml version="1.0" encoding="utf-8"?>
<rss
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:media="http://search.yahoo.com/mrss/"
    xmlns:mi="http://schemas.ingestion.microsoft.com/common/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:dcterms="http://purl.org/dc/terms/" version="2.0">
    <channel>
        <title>A</title>
        <item>
            <title>title1</title>
            <dc:creator>creator1</dc:creator>
        </item>
        <item>
            <title>title2</title>
            <dc:creator>creator2</dc:creator>
        </item>
    </channel>
</rss>'''

root = ET.fromstring(xml_string)

for item in root.findall('channel'):
    title = item.find('title').text
    print(title)
for item2 in root.findall('channel/item'):
    title = item2.find('title').text
    print(title)
    creator = item2.find('.//dc:creator', namespaces = {'dc': 'http://purl.org/dc/elements/1.1/'}).text
    print(creator)

  

posted @ 2024-04-29 11:05  亿逍遥  阅读(18)  评论(0编辑  收藏  举报