Python3 parse xml

六月ゝ 毕业季﹏ 提交于 2019-12-10 16:23:57

问题


I tried to parse XML using different python3 modules and different articles from internet but not success.

I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:cwmp="urn:dslforum-org:cwmp-1-0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><SOAP-ENV:Header/>
<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<cwmp:GetParameterValuesResponse>
    <ParameterList SOAP-ENC:arrayType="cwmp:ParameterValueStruct[3]">
        <ParameterValueStruct>
            <Name>SOME_NAME_1_HERE</Name>
            <Value>2</Value>
        </ParameterValueStruct>
        <ParameterValueStruct>
            <Name>SOME_NAME_2_HERE</Name>
            <Value>180</Value>
        </ParameterValueStruct>
        <ParameterValueStruct>
            <Name>SOME_NAME_3_HERE</Name>
            <Value>1800</Value>
        </ParameterValueStruct>
    </ParameterList>
</cwmp:GetParameterValuesResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I need to take data from XML tags: Name and Value It should be something like:

SOME_NAME_1_HERE 2
SOME_NAME_2_HERE 180
SOME_NAME_3_HERE 1800

How I can get this values using Python3(will be good to use python default modules - not bs4)?

Thanks


回答1:


Using xml.etree you can execute simple XPath expression .//element_name to find element anywhere within a given context element :

from xml.etree import ElementTree as ET
tree = ET.parse('path_to_your_xml.xml')
root = tree.getroot()

for p in root.findall('.//ParameterValueStruct'):
    print("%s | %s" % (p.find('Name').text, p.find('Value').text))



回答2:


You can try something like this :

import xml.etree.ElementTree
e = xml.etree.ElementTree.parse('Newfile.xml').getroot()

print(e)
for atype in e.findall('.//ParameterValueStruct'):
    print("%s | %s" % (atype.find('Name').text, atype.find('Value').text))


来源:https://stackoverflow.com/questions/43589769/python3-parse-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!