如何使用 python 添加 xml 格式的用户名和密码

How to add username and password for xml format with python

def test(login,password):
    data="""<?xml version="1.0"?>
        <soap-env>
        <soap-env:Body>
        <Auth>
        <Login>login</Login><password>password</password>
        </Auth>
        <Ping>
        </Ping>
        </soap-env:Body>
        </soap-env:Envelope>"""
    return data

我无法在使用“+login+”时添加登录名和密码,也无法像这样格式化字符串“”

试试下面的('f' 字符串)

def test(login,password):
    data=f"""<?xml version="1.0"?>
        <soap-env>
        <soap-env:Body>
        <Auth>
        <Login>{login}</Login><password>{password}</password>
        </Auth>
        <Ping>
        </Ping>
        </soap-env:Body>
        </soap-env:Envelope>"""
    return data

print(test('jack','secret'))

输出

<?xml version="1.0"?>
        <soap-env>
        <soap-env:Body>
        <Auth>
        <Login>jack</Login><password>secret</password>
        </Auth>
        <Ping>
        </Ping>
        </soap-env:Body>
        </soap-env:Envelope>

如果您看到数据是 XML,您 必须 使用 XML 模块来构建它。构建看起来像 XML 的字符串不是一个好主意,因为它很容易违反标准。这是如何使用内置 (should) 完成的 xml.etree.ElementTree:

import xml.etree.ElementTree as ET

def test(login, password):
    envelope_uri = "http://schemas.xmlsoap.org/soap/envelope/"
    ET.register_namespace("soap-env", envelope_uri)
    envelope_node = ET.Element(ET.QName(envelope_uri, "Envelope"))
    body_node = ET.SubElement(envelope_node, ET.QName(envelope_uri, "Body"))
    auth_node = ET.SubElement(body_node, "Auth")
    ET.SubElement(auth_node, "Login").text = login
    ET.SubElement(auth_node, "Password").text = password
    ET.SubElement(body_node, "Ping")

    # ET.indent(envelope_node)  # uncomment this to get indented output (python 3.9+)
    return ET.tostring(
        envelope_node,  # root node
        "utf-8",  # encoding
        xml_declaration=True,  # add xml declaration on top
        short_empty_elements=False  # use start/end pair for empty nodes
    ).decode()

print(test("login",  "p<>&sword"))

此代码将产生下一个输出:

<?xml version='1.0' encoding='utf-8'?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
  <soap-env:Body>
    <Auth>
      <Login>login</Login>
      <Password>p&lt;&gt;&amp;sword</Password>
    </Auth>
    <Ping></Ping>
  </soap-env:Body>
</soap-env:Envelope>

这是有效XML(proof).

来自 的具有相同参数的函数将产生下一个输出:

<?xml version="1.0"?>
        <soap-env>
        <soap-env:Body>
        <Auth>
        <Login>login</Login><password>p<>&sword</password>
        </Auth>
        <Ping>
        </Ping>
        </soap-env:Body>
        </soap-env:Envelope>

这是无效的XML(proof).