如何使用Python将字符串匹配到映射xml标签? [英] How to match a string to mapping xml tag using Python?

查看:89
本文介绍了如何使用Python将字符串匹配到映射xml标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从XML文件映射一个值.

I would like to map a value from an XML file.

<Country>
     <number no="2008" info="update">
          <detail name="man1" class="A1\X4">
               <string name="ruth" />
               <string name="amy" />
          </detail>
          <detail name="man2" class="A2">
               <string name="lisa" />
               <string name="graham" />
          </detail>
     </number>
</Country>

我需要在此处

I need to get the value of the number in here <number no="2008" by mapping with this value class="A1\X4"

T尝试过这种方式:

stringno = 'A1'
for family in ReadXML.findall('number/detail[@class="{}"]/..'.format(stringno)):
    name = family.get('no')
    print(name)

仅在 stringno ="A1 \ X4" 时有效.但是如果 stringno ='A1',我需要将其映射.python中是否有任何匹配功能可以解决此问题?也许像一样 -contain ?

it only works if the stringno="A1\X4". But I need to mapping it if the stringno = 'A1'. Is there any matching function in python to solve this problem? maybe -like or -contain?

感谢您提供的信息.

推荐答案

您好,如何使用迭代方法.

Hi what about using an iterative method.

完整代码

import xml.etree.ElementTree as ET

tree = ET.parse('myXml.xml')
root = tree.getroot()

stringno = 'A1'

for family in root.findall('number'):
    for elem in family:
        if stringno in elem.get('class'):
            print('no: {}, name: {}, class: {}'.format(family.get('no'), elem.get('name'), elem.get('class')))

输入

myXml.xml

myXml.xml

<Country>
     <number no="2008" info="update">
          <detail name="man1" class="A1\X4">
               <string name="ruth" />
               <string name="amy" />
          </detail>
          <detail name="man2" class="A2">
               <string name="lisa" />
               <string name="graham" />
          </detail>
     </number>
     <number no="2009" info="update">
          <detail name="man1" class="A1\X5">
               <string name="ruth" />
               <string name="amy" />
          </detail>
          <detail name="man2" class="A3">
               <string name="lisa" />
               <string name="graham" />
          </detail>
     </number>
</Country>

输出

no: 2008, name: man1, class: A1\X4
no: 2009, name: man1, class: A1\X5

这篇关于如何使用Python将字符串匹配到映射xml标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆