【问题标题】:Python3 parse xmlPython3解析xml
【发布时间】:2017-09-21 05:37:10
【问题描述】:

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

我有这个 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 标签中获取数据:名称和值 它应该是这样的:

SOME_NAME_1_HERE 2
SOME_NAME_2_HERE 180
SOME_NAME_3_HERE 1800

如何使用 Python3 获取这些值(最好使用 python 默认模块 - 而不是 bs4)?

谢谢

【问题讨论】:

    标签: xml python-3.x xml-parsing


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢,您的代码有效。但在 PRINT 上有一些变化。
    【解决方案2】:

    你可以试试这样的:

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

    【讨论】:

    • 谢谢,但您的代码什么也没打印。 /usr/bin/python3.5 /home/ppikh/Desktop/test.py Process finished with exit code 0
    • e.findall('.//ParameterValueStruct')
    • @har07 在你的情况下,我收到:每次打印都没有
    • @PetroPikh get() 应该用于读取 XML 属性。改用find() 来获取单个XML 元素,然后从text 属性中获取元素的内部文本。见其他答案..
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2020-12-03
    • 2020-03-20
    • 1970-01-01
    相关资源
    最近更新 更多