xml.etree.ElementTree findall 函数返回路径的空字符串 python

问题描述 投票:0回答:1

给定XML为字符串。

xml_as_string = """<root xmlns:SOAP-ENV="http://w/e">
    <Context operation="something.wsdl">
        <SOAP_Version>123.321</SOAP_Version>
        <Namespace xmlns:SOAP-ENV="http://dummy.com"/>
    </Context>
    <Header/>
    <Body>
        <ns2:Complex xmlns:ns2="http://www.test.this/idk">
            <ns2:simple>
                <ns2:child1>IKM</ns2:child1>
                <ns2:child2>1234</ns2:child2>
                <ns2:child3>S</ns2:child3>
            </ns2:simple>
            <ns2:simple>
                <ns2:child1>QEw</ns2:child1>
                <ns2:child2>10028111</ns2:child2>
                <ns2:parentchild1>IKM</ns2:parentchild1>
                <ns2:parentchild2>1234</ns2:parentchild2>
                <ns2:child3>S</ns2:child3>
            </ns2:simple>
            <ns2:simple>
                <ns2:child1>IOW</ns2:child1>
                <ns2:child2>100043896</ns2:child2>
                <ns2:parentchild1>QEw</ns2:parentchild1>
                <ns2:parentchild2>10028111</ns2:parentchild2>
            </ns2:simple>
            <ns2:extra>
                <ns2:childextra>0</ns2:childextra>
            </ns2:extra>
        </ns2:Complex>
    </Body>
</root>
"""

使用xml.etree.ElementTree创建xml树。

`import xml.etree.ElementTree as ET`

root = ET.fromstring(xml_as_string)

对于一个特定的路径,我试图打印所有找到的值。

path = './Body/Complex/simple/child1'

path_vals = root.findall(path)
print([e.text for e in path_vals])

结果是一个空列表。

[]

有什么方法可以在python中实现这个功能吗?

python xml elementtree xml.etree
1个回答
1
投票

你可能想要所有与child1相关联的文本:你需要使用的是 命名空间 来获取数据。"http:/www.test.thisidk"是命名空间

namespace = '{http:/www.test.thisidk}'

[ent.text for ent in root.findall(F".//{namespace}child1")]

['IKM', 'QEw', 'IOW']

如果你想取消命名空间,你可以给它一个 旁听生 一去

from parsel import Selector
selector = Selector(xml_as_string, 'xml')

#remove namespace
selector.remove_namespaces()

#get ur required text
selector.xpath(".//child1/text()").getall()

['IKM', 'QEw', 'IOW']
© www.soinside.com 2019 - 2024. All rights reserved.