Python操作并保存XML,更改一个属性

2024-04-19 16:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个xml:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SOAP-ENV:Body>
        <m:request xmlns:m="http://www.datapower.com/schemas/management" domain="XXXXX">
            <m:do-action>
                <FlushDocumentCache>
                    <XMLManager class="XMLManager">default</XMLManager>
                </FlushDocumentCache>
                <FlushStylesheetCache>
                    <XMLManager class="XMLManager">default</XMLManager>
                </FlushStylesheetCache>
            </m:do-action>
        </m:request>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

我只想更改域属性的值XXXXX。在

我做了这样的事:

^{pr2}$

谢谢。在


Tags: orgenvhttprequestwwwbodyschemassoap
1条回答
网友
1楼 · 发布于 2024-04-19 16:24:59

几句话:

  • 您将看到,解析xml字符串(从文件)并将其写入另一个文件不会产生相同的结果,因为解析器会更改它。您可以通过运行您发布的代码(显然是第三行代码)来测试它:

    import xml.etree.ElementTree as etree
    tree = etree.parse('input.xml')
    tree.write('output.xml')
    
  • 和所有节点。为此,我必须将它们从xml文件复制到代码(soap_env_ns_name和{}变量),如下所述:Saving XML using ETree in Python. It's not retaining namespaces, and adding ns0, ns1 and removing xmlns tags

  • SOAP-ENC和默认名称空间(xsixsd)已被删除,因为它们在xml中没有被引用。另外,m已经从请求节点移到信封(根)节点;我不确定它是否是标准的一部分,但在大多数XML中,名称空间都是在根节点中声明的。不管怎样,这里没有什么你能做的,Python的解析器不是很聪明。

  • 底线是您不会得到完全相同的输出(除非您想编写自己的解析器,如下所述:Python: Update XML-file using ElementTree while conserving layout as much as possible)。在

因此,代码对XML结构非常严格(丑陋但不是最丑的),如果结构发生变化,代码也需要更新(这里我不是在讨论名称空间的解决方法):

@EDIT1:添加了for循环来注册名称空间,以前的版本与我在第2个项目符号中描述的一样。但是在运行它时,它确实用Ys替换了Xs

@EDIT2:注释掉了domain属性值测试,所以现在该值仍将更改。在

^{pr2}$

相关问题 更多 >