编辑现有 XML 文件并通过 Jboss 发送 post

Editing existing XML file and sending post via Jboss

我有以下 python 方法,它运行 xml 文件并解析它,TRIES 来编辑字段:

    import requests
import xml.etree.ElementTree as ET
import random

def runThrougheTree():
    #open xml file
    with open("testxml.xml") as xml:
        from lxml import etree
        #parse
        parser = etree.XMLParser(strip_cdata=True, recover=True)
        tree = etree.parse("testxml.xml", parser)
        root= tree.getroot()
        #ATTEMPT to edit field - will not work as of now
        for ci in root.iter("CurrentlyInjured"):
            ci.text = randomCurrentlyInjured(['sffdgdg', 'sdfsdfdsfsfsfsd','sfdsdfsdfds'])
        #Overwrite initial xml file with new fields  - will not work as of now
        etree.ElementTree(root).write("testxml.xml",pretty_print=True, encoding='utf-8', xml_declaration=True)

        #send post (Jboss)
        requests.post('http://localhost:9000/something/RuleServiceImpl', data="testxml.xml)



def randomCurrentlyInjured(ran):
    random.shuffle(ran)
    return ran[0]







#-----------------------------------------------
if __name__ == "__main__":
    runThrougheTree()

已编辑 XML 文件:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rule="http://somewebsite.com/" xmlns:ws="http://somewebsite.com/" xmlns:bus="http://somewebsite.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:Respond>
         <ws:busMessage>
            <bus:SomeRef>insertnumericvaluehere</bus:SomeRef>
            <bus:Content><![CDATA[<SomeDef>
  <SomeType>ABCD</Sometype>
  <A_Message>
      <body>
        <AnonymousField>
          <RefIndicator>1111111111111</RefIndicator>
          <OneMoreType>HIJK</OneMoreType>
          <CurrentlyInjured>ABCDE</CurentlyInjured>
        </AnonymousField>
      </body>
  </A_Message>
</SomeDef>]]></bus:Content>
            <bus:MessageTypeId>somenumericvalue</bus:MessageTypeId>
         </ws:busMessage>
      </ws:Respond>
   </soapenv:Body>
</soapenv:Envelope>

问题:

  1. 该字段未被编辑。
  2. Jboss 错误:由以下原因引起:javax.xml.stream.XMLStreamException:[row,col] 处的 ParseError:[1,1] 消息:序言中不允许内容。

注意:我已确保第一个 xml 标记之前没有字符。

最后,我无法使用 lxml, elementtree 将 fields/post 编辑为 Jboss as:

  1. 正如 mzjn 在评论中指出的那样,我在 xml 中有 CDATA

  2. Jboss 不喜欢解析后的请求,即使删除了 CDATA 标签。

Workaround/Eventual 解决方案:我能够(有点乏味地)在我的脚本中使用 .replace() 来成功编辑明文,然后通过 Jboss 发送 POST。我希望有一天这能帮助别人!