python - 无法使用 ElementTree 修改 XML 正文中 CDATA 中的内容
问题描述
我目前正在尝试在我创建的 python 脚本中将 XML 文件发布到 Jboss,但是在执行 POST 方法时遇到与 jboss 控制台上的命名空间相关的错误。
注意:在尝试 POST 之前,我使用 ElementTree 来解析 XML/更改 XML 正文中的一些字段。
注意:当在 SOAPUI 中(成功地)发送请求(见下文)时,xml 主体周围有一些soap 标头,我已将这些标头排除在我正在读取的 xml 文件中,以便根据需要解析/编辑 xml。
我的目标是:
- 找到一种在解析之前简单地在 XML 文件中包含肥皂头的方法(如果我当前包含它们,ElementTree 将不会编辑 XML)
或者
- 在排除了肥皂标题的元素上消除“无命名空间”错误。
脚本中发布请求的方法:
def fire_post_request():
xml_file = "updated.xml"
headers = {'Content-Type':'text/xml'}
# Open the XML file.
with open(xml_file) as xml:
# Give the object representing the XML file to requests.post.
r = requests.post('http://localhost:8000/path/to/whererulesserviceisrunning', data=xml)
print (r.content)
Jboss 控制台上的错误:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:VersionMismatch</faultcode><faultstring>No namespace on "SomeDefinition" element.</faultstring></soap:Fault></soap:Body></soap:Envelope>
当前没有环绕soap头的XML结构(parsedxml.xml):
<SomeDefinition>
<Channel>....</Channel>
<Rulesmsg>
<body>
....
</body>
</service>
</Rulesmsg>
</SomeDefinition>
我从 XML 文件中排除的 Soap 标头,因为使用它们,ElementTree 不允许我编辑 XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rule="somewebsitepath0" xmlns:ws="somewebsitepath1" xmlns:buss="somewebsitepath2">
<soapenv:Header/>
<soapenv:Body>
<ws:Respond>
<ws:Message>
<buss:SourceReference>11122</buss:SourceReference>
<buss:Content>**<![CDATA[**
.....XML BODY WOULD GO HERE.....
**]]>**</bus:Content>
<bus:MessageTypeId>3243242</bus:MessageTypeId>
</ws:Message>
</ws:Respond>
</soapenv:Body>
</soapenv:Envelope>
解决方案
此问题与使用 ElementTree 后无法将 CDATA 保留为 CDATA 有关。我最终根据我的要求使用 lxml 库来保留 CDATA。
推荐阅读
- sql - 在 SQL Server 上使用 INNER JOIN 进行更新
- powershell - 调用 Pester 返回零结果
- javascript - 执行 AJAX 调用序列时显示自定义消息加载器的最佳方式是什么?
- javascript - 使用基于复选框(真/假)表单输入的全局变量更新 JS 数组值
- list - Haskell:合并一个列表,其中偶数索引来自列表 1,奇数索引来自列表 2。如果大小不同,则填充 0
- odoo - Odoo 资产未加载
- html - 按照推荐的文档,引导切换按钮不起作用
- neural-network - 什么类型的文本相似性自动编码器?
- c# - 带有从左到右移动文本的新闻自动收报机
- keras - 使用 keras 的自动编码器,具有固定的权重