gpt4 book ai didi

python lxml元素属性问题

转载 作者:太空宇宙 更新时间:2023-11-03 21:12:56 24 4
gpt4 key购买 nike

我必须构建一个如下所示的 XML 文件:

<?xml version='1.0' encoding='ISO-8859-1'?>
<Document protocol="OCI" xmlns="C">
<sessionId>xmlns=874587878</sessionId>
<command xmlns="http://www.w3.org/2001/XMLSchema-instance" xsi:type="UserGetRegistrationListRequest">
<userId>data</userId>
</command>
</Document>

除了命令 attrib 之外,我一切正常 xsi:type="UserGetRegistrationListRequest"

我无法在命令元素的属性中获取 :

有人可以帮我解决这个问题吗?

我使用的是 Python 3.5。

我当前的代码是

from lxml import etree


root = etree.Element("Document", protocol="OCI", xmlns="C")
print(root.tag)
root.append(etree.Element("sessionId") )
sessionId=root.find("sessionId")
sessionId.text = "xmlns=78546587854"
root.append(etree.Element("command", xmlns="http://www.w3.org/2001/XMLSchema-instance",xsitype = "UserGetRegistrationListRequest" ) )
command=root.find("command")
userID = etree.SubElement(command, "userId")
userID.text = "data"
print(etree.tostring(root, pretty_print=True))
tree = etree.ElementTree(root)
tree.write('output.xml', pretty_print=True, xml_declaration=True, encoding="ISO-8859-1")

然后我就得到了这个

   <?xml version='1.0' encoding='ISO-8859-1'?>
<Document protocol="OCI" xmlns="C">
<sessionId>xmlns=78546587854</sessionId>
<command xmlns="http://www.w3.org/2001/XMLSchema-instance" xsitype="UserGetRegistrationListRequest">
<userId>data</userId>
</command>

最佳答案

QName 可用于创建 xsi:type 属性。

from lxml import etree

root = etree.Element("Document", protocol="OCI", xmlns="C")

# Create sessionId element
sessionId = etree.SubElement(root, "sessionId")
sessionId.text = "xmlns=78546587854"

# Create xsi:type attribute using QName
xsi_type = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "type")

# Create command element, with xsi:type attribute
command = etree.SubElement(root, "command", {xsi_type: "UserGetRegistrationListRequest"})

# Create userId element
userID = etree.SubElement(command, "userId")
userID.text = "data"

生成的 XML(具有正确的 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 声明):

<?xml version='1.0' encoding='ISO-8859-1'?>
<Document protocol="OCI" xmlns="C">
<sessionId>xmlns=78546587854</sessionId>
<command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="UserGetRegistrationListRequest">
<userId>data</userId>
</command>
</Document>

请注意,xsi 前缀不需要在 Python 代码中显式定义。 lxml 为一些众所周知的命名空间 URI 定义了默认前缀,包括 http://www.w3.org/2001/XMLSchema-instancexsi

关于python lxml元素属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54926560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com