首页 > 解决方案 > 无法使用 ElementTree 修改 XML 正文中 CDATA 中的内容

问题描述

我目前正在尝试在我创建的 python 脚本中将 XML 文件发布到 Jboss,但是在执行 POST 方法时遇到与 jboss 控制台上的命名空间相关的错误。

注意:在尝试 POST 之前,我使用 ElementTree 来解析 XML/更改 XML 正文中的一些字段。

注意:当在 SOAPUI 中(成功地)发送请求(见下文)时,xml 主体周围有一些soap 标头,我已将这些标头排除在我正在读取的 xml 文件中,以便根据需要解析/编辑 xml。

我的目标是:

  1. 找到一种在解析之前简单地在 XML 文件中包含肥皂头的方法(如果我当前包含它们,ElementTree 将不会编辑 XML)

或者

  1. 在排除了肥皂标题的元素上消除“无命名空间”错误。

脚本中发布请求的方法:

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>

标签: pythonxmljbosselementtree

解决方案


此问题与使用 ElementTree 后无法将 CDATA 保留为 CDATA 有关。我最终根据我的要求使用 lxml 库来保留 CDATA。


推荐阅读