【发布时间】:2019-02-28 13:11:30
【问题描述】:
我必须构建一个如下所示的 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>
【问题讨论】:
-
How to create a Minimal, Complete, and Verifiable example 将帮助我们回答您的问题。但是,拥有
xsi:type属性而不将xsi前缀绑定到命名空间会使您的 XML 的命名空间格式不正确。xmlns="http://www.w3.org/2001/XMLSchema-instance"需要是xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"。
标签: python xml python-3.x lxml xml-namespaces