使用“信息获取“对于Python/lxm中的子元素

2024-04-28 00:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用lxml在Python中获取子元素的属性。你知道吗

这是xml的结构:

<GroupInformation groupId="crid://thing.com/654321" ordered="true">                 
    <GroupType value="show" xsi:type="ProgramGroupTypeType"/>               
    <BasicDescription>              
        <Title type="main" xml:lang="EN">A programme</Title>            
        <RelatedMaterial>           
        <HowRelated href="urn:eventis:metadata:cs:HowRelatedCS:2010:boxCover">      
            <Name>Box cover</Name>  
        </HowRelated>       
        <MediaLocator>      
            <mpeg7:MediaUri>file://ftp.something.com/Images/123456.jpg</mpeg7:MediaUri> 
        </MediaLocator>     
    </RelatedMaterial>          
</BasicDescription>             

你知道吗

我得到的代码如下。我要返回的位是'grouptype'(底部第三行)下的'value'属性(“示例中的Show”):

file_name = input('Enter the file name, including .xml extension: ') 
print('Parsing ' + file_name)

from lxml import etree
parser = etree.XMLParser()

tree = etree.parse(file_name, parser)                               
root = tree.getroot()

nsmap = {'xmlns': 'urn:tva:metadata:2010','mpeg7':'urn:tva:mpeg7:2008'} 

with open(file_name+'.log', 'w', encoding='utf-8') as f:  
    for info in root.xpath('//xmlns:GroupInformation', namespaces=nsmap):
       crid = info.get('groupId'))                                     
       grouptype = info.find('.//xmlns:GroupType', namespaces=nsmap)
       gtype = grouptype.get('value')
       titlex = info.find('.//xmlns:BasicDescription/xmlns:Title', namespaces=nsmap)
       title = titlex.text if titlex != None else 'Missing'

有人能给我解释一下怎么实施吗?我快速查看了xsi名称空间,但无法让它工作(不知道这样做是否正确)。你知道吗


Tags: nameinfotitlevaluexmlfileetreenamespaces
1条回答
网友
1楼 · 发布于 2024-04-28 00:54:18

这就是你要找的吗?你知道吗

grouptype.attrib['value']

PS:为什么在赋值周围加括号?那些看起来没必要。你知道吗

相关问题 更多 >