python-3.x - 如何在 Python 3.7.3 中解析没有命名空间的 xml-string(不是文件)?
问题描述
我正在将字符串转换为 xml。如何解析没有命名空间的 XML?也许您可以建议其他库使用 XML 字符串?
这是我的代码:
import xml.etree.ElementTree as ET
country_data_as_string = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:aa="http://vio.pfr.ru/Statements/ApplyApplication/1.0"><soap:Header><wsa:MessageID>12fd0e5b78cf44c2a61a1c6fc238cc51</wsa:MessageID><wsa:Action>http://vio.pfr.ru/person/Application/MSKApplicationPortType/ApplyApplicationRequest</wsa:Action><GlobalProcessID>66826749770843f4bfc5f359a86165af</GlobalProcessID></soap:Header></soap:Envelope>'
doc = ET.fromstring(country_data_as_string)
for elem in doc:
for i in elem:
print(i)
if i.tag == 'MessageID':
print(i)
解决方案
以下代码将允许您在不使用命名空间模式的情况下读取整个xml :
import xml.etree.ElementTree as ET
country_data_as_string = r"""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:aa="http://vio.pfr.ru/Statements/ApplyApplication/1.0">
<soap:Header>
<wsa:MessageID>12fd0e5b78cf44c2a61a1c6fc238cc51</wsa:MessageID>
<wsa:Action>http://vio.pfr.ru/person/Application/MSKApplicationPortType/ApplyApplicationRequest</wsa:Action>
<GlobalProcessID>66826749770843f4bfc5f359a86165af</GlobalProcessID>
</soap:Header>
</soap:Envelope>
"""
doc = ET.fromstring(country_data_as_string)
for node in doc.iter():
print(node.tag+': ', node.text) # node.text has the data encompassed by the tags
上面的输出:
{http://www.w3.org/2003/05/soap-envelope}Envelope:
{http://www.w3.org/2003/05/soap-envelope}Header:
{http://schemas.xmlsoap.org/ws/2004/08/addressing}MessageID: 12fd0e5b78cf44c2a61a1c6fc238cc51
{http://schemas.xmlsoap.org/ws/2004/08/addressing}Action: http://vio.pfr.ru/person/Application/MSKApplicationPortType/ApplyApplicationRequest
GlobalProcessID: 66826749770843f4bfc5f359a86165af
推荐阅读
- php - 将内容添加到 WooCommerce 我的帐户仪表板主页部分
- node.js-typeorm - 如何在@TreeParent 上使用自定义数据库列名
- c# - 如何区分 HttpClient.CancelPendingRequests 和 CancellationTokenSource
- mysql - 事务提交/回滚执行问题
- php - 如果名称字符串中有字符,则以名称的形式在字符串中添加一个点
- python - Python 抱怨在一个线程中创建的 SQLite 对象只能在那个线程中使用,但我没有尝试访问任何其他线程中的任何 SQLite 对象
- tensorflow - 我正在为聊天机器人编写一个 python 脚本,我收到了这个错误
- python - 执行期间跳过 Python 函数
- react-native - 无法使用 npm 更新 React 和 React Native
- python - 使用 uuid.uuid4() 作为默认值