Python3解析xml [英] Python3 parse xml

查看:31
本文介绍了Python3解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用不同的 python3 模块和来自互联网的不同文章解析 XML,但没有成功.

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

我有这个 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>

我需要从 XML 标签中获取数据:名称和值它应该是这样的:

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

我如何使用 Python3 获取这些值(使用 Python 默认模块会很好 - 而不是 bs4)?

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

谢谢

推荐答案

使用 xml.etree 您可以执行简单的 XPath 表达式 .//element_name 来查找其中任何位置的元素给定的上下文元素:

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))

这篇关于Python3解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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