python - 在Python中解析XML

标签 python xml

我收到此 xml 响应,任何人都可以帮助我从 xml 标签获取 token 吗?

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><LoginResponse xmlns="http://videoos.net/2/XProtectCSServerCommand"><LoginResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><RegistrationTime>2018-09-06T07:30:38.4571763Z</RegistrationTime><TimeToLive><MicroSeconds>3600000000</MicroSeconds></TimeToLive><TimeToLiveLimited>false</TimeToLiveLimited><Token>TOKEN#xxxxx#</Token></LoginResult></LoginResponse></s:Body></s:Envelope> 

我把它作为字符串

也尝试过 lxml 和其他库(例如 ET),但无法提取 token 字段。求助

使用 xml 格式进行更新,以便于阅读,仅供引用。

<?xml version="1.0" encoding="utf-8"?>

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <LoginResponse xmlns="http://videoos.net/2/XProtectCSServerCommand">
      <LoginResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <RegistrationTime>2018-09-06T07:30:38.4571763Z</RegistrationTime>
        <TimeToLive>
          <MicroSeconds>3600000000</MicroSeconds>
        </TimeToLive>
        <TimeToLiveLimited>false</TimeToLiveLimited>
        <Token>TOKEN#xxxxx#</Token>
      </LoginResult>
    </LoginResponse>
  </s:Body>
</s:Envelope>

最佳答案

text  = """
<?xml version="1.0" encoding="utf-8"?>

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <LoginResponse xmlns="http://videoos.net/2/XProtectCSServerCommand">
      <LoginResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <RegistrationTime>2018-09-06T07:30:38.4571763Z</RegistrationTime>
        <TimeToLive>
          <MicroSeconds>3600000000</MicroSeconds>
        </TimeToLive>
        <TimeToLiveLimited>false</TimeToLiveLimited>
        <Token>TOKEN#xxxxx#</Token>
      </LoginResult>
    </LoginResponse>
  </s:Body>
</s:Envelope>
"""
from bs4 import BeautifulSoup

parser = BeautifulSoup(text,'xml')
for item in parser.find_all('Token'):
    print(item.text)

关于python - 在Python中解析XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52198872/

相关文章:

python - 为什么即使已经安装了 Scrapy 模块,python 也会抛出 "ImportError: No module named linkextractor"?

python - 为什么 os.system 无法重定向到文件?如何启用它?

java - JAXB 解码一个集合

c - 哪个更好? XML、INI 或其他什么?

c# - 在 C# 中将 XML 文件解析为字符串

python - 如何使用 Mysql Python 连接器检索二进制数据?

python - 将 Python AES 转换为 Node

python - 如何进行具有多个过滤器的 Django 数据库查询?

xml - Docbook XML 到 PDF,没有 'ő' 和 'ű' 字符

python - ElementTree,Python - 查找子元素包含特定文本的元素并将另一个子元素添加到列表中