用于检查条件和输出标签的XML,PYTHON

时间:2017-09-27 18:00:12

标签: python xml

我有一个xml文件,如下所示:

   <records>
   <record>
        <device_serial_number>PAD203146024</device_serial_number>
        <device_serial_number_2>203146024</device_serial_number_2>
        <docsis_mac>6412695EB9BB</docsis_mac>
   </record>
   <record>
        <device_serial_number>PAD206024</device_serial_number>
        <device_serial_number_2>20324</device_serial_number_2>
        <docsis_mac>6412BB</docsis_mac>
   </record>
   </records>

我在python中使用ETree读取这个xml文件并运行良好,现在我想检查标签是否有以&#34; PAD&#34;开头的文本。如果它然后输出如下:

    Expected output
    <record>
    <device_serial_number>PAD203146024</device_serial_number>
    <device_serial_number_2>203146024</device_serial_number_2>
    <docsis_mac>6412695EB9BB</docsis_mac>
    </record>

1 个答案:

答案 0 :(得分:1)

import xml.etree.ElementTree as ET

recs=[ET.tostring(c) for c in record if c.find('device_serial_number').text[:3]=='PAD']
for rec in recs:
   print(rec)

其中record以上是for循环中的record元素,如您的问题所示。如果 'device_serial_number'PAD开头,则应该返回的记录,如下所示: -

<record>
        <device_serial_number>PAD203146024</device_serial_number>
        <device_serial_number_2>203146024</device_serial_number_2>
        <docsis_mac>6412695EB9BB</docsis_mac>
   </record>

<record>
        <device_serial_number>PAD206024</device_serial_number>
        <device_serial_number_2>20324</device_serial_number_2>
        <docsis_mac>6412BB</docsis_mac>
   </record>

如果任何记录元素作为孩子没有device_serial_number,那么我会使用以下内容:

   from xml.etree import ElementTree as ET
   from xml.dom.minidom import parseString

   tree = ET.parse('C:\\Use\\CO.xml')
   root = tree.getroot()
   for record in root.findall('records'):
       recs=[c for c in t if c.find('device_serial_number')!=None and c.find('device_serial_number').text[:3]=='PAD']
       for rec in recs:
          print(parseString(ET.tostring(rec)).toprettyxml(''))