python lxml元素attrib问题

问题描述 投票:1回答:1

我必须构建一个类似于以下内容的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>

python xml python-3.x lxml xml-namespaces
1个回答
0
投票

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>

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

© www.soinside.com 2019 - 2024. All rights reserved.