【问题标题】:xml.etree.ElementTree findall function returns empty string for path pythonxml.etree.ElementTree findall 函数为路径 python 返回空字符串
【发布时间】:2020-09-23 07:40:26
【问题描述】:

给定 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】:

您可能想要与 child1 关联的所有文本:您需要使用 namespace 来获取数据:“http://www.test.this/idk”是命名空间

namespace = '{http://www.test.this/idk}'

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

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

如果你想取消命名空间,你可以试试parsel

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

#remove namespace
selector.remove_namespaces()

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

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

【讨论】:

  • 你可以将它作为变量传递,然后使用 fstrings。
  • 嗯,那么理想情况下,我更喜欢忽略命名空间或自行计算出来的东西,嗯,查看 lxml rn,也许,只是也许
  • 编辑代码,使用parsel
  • 在 Python 3.8 中使用 ElementTree,您可以为命名空间使用通配符。示例:stackoverflow.com/a/62117710/407651.
猜你喜欢
  • 2021-10-09
  • 1970-01-01
  • 2016-09-07
  • 2014-06-07
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2014-12-07
  • 2017-05-05
相关资源
最近更新 更多