Python读取xml内部标记

时间:2017-06-12 05:56:58

标签: python xml

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <child1>
        <details id="1">
         <name ab="1">Ram</name>
         <age ab="2">45</age>
         <phone>
            <phone1>777777777</phone1>
        </phone>    
    </child1>    
        </details> 
    <child2>
        <details id="2">
            <name ab="3">kiran</name>
            <age ab="4">57</name>
            <phone>
                <phone1>888888888</phone1>
            </phone>    
        </details>
    <child2>
</parent>   
  

如果我给出了输入2,它应该返回child2的详细信息,即

     

o / p应该是

     

详情id =&#34; 2&#34;

     

姓名ab 3 kiran年龄4 4 57电话888888888888

     

如果我给出了输入1,它应该返回child1的详细信息,依此类推。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

import xml.etree.ElementTree as ET

my_xml = 'some_xml.xml'

tree = ET.parse(my_xml)

root = tree.getroot()

id = str(input('Enter id: '))

for element in root:
if element.tag == 'child' + id:
    details = element.find('details')
    for detail in details:
        if detail.tag == 'phone':
            continue
        else:
            print('{} : {}'.format(detail.tag, detail.text))
    phones = details.find('phone')
    for phone in phones:
        print('{} : {}'.format(phone.tag, phone.text))

xml位于文件some_xml.xml中,与python代码位于同一目录中。顺便说一下,你的xml文件不正确。它应该是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <child1>
        <details id="1">
         <name ab="1">Ram</name>
         <age ab="2">45</age>
         <phone>
            <phone1>777777777</phone1>
         </phone>    
        </details> 
    </child1>    
    <child2>
        <details id="2">
            <name ab="3">kiran</name>
            <age ab="4">57</age>
            <phone>
                <phone1>888888888</phone1>
            </phone>    
        </details>
    </child2>
</parent>   

修复你的,应该可以正常工作。

请注意,xml.etree.ElementTree模块对于恶意构造的数据不安全,如文档中所述。

相关问题