【问题标题】:python process xml string with namespacespython处理带有命名空间的xml字符串
【发布时间】:2019-09-24 19:05:36
【问题描述】:

我有以下带有命名空间的 XML。

<ns:loginResponse xmlns:ns="http://sumo.fsg.gre.ac.uk">
    <ns:return xmlns:ax21="http://sumo.fsg.gre.ac.uk/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:type="ax21:Authorisation_LoginResults">
        <ax21:key>key</ax21:key>
        <ax21:lastAccess>1569262077707</ax21:lastAccess>
        <ax21:success>true</ax21:success>
    </ns:return>
</ns:loginResponse>

我需要在 python 中处理这段代码。我已经阅读了 https://docs.python.org/2/library/xml.etree.elementtree.html 的 ElementTree XML API 教程,但我不明白如何访问标签 ax21:key、ax21:lastaccess 等中的值。

将不胜感激在 python 中访问这些元素的一些代码 sn-p。

【问题讨论】:

    标签: python xml namespaces


    【解决方案1】:

    尝试使用 Beautifulsoup 解析 xml:

    from bs4 import BeautifulSoup
    with open(r"test.xml","r",encoding='utf8') as f:
        content = f.read()
        soup = BeautifulSoup(content,'html.parser')
        for tag in soup.find_all('ax21:key'):
            print(tag.get_text())
    

    【讨论】:

      猜你喜欢
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2021-10-24
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多