Проблема атрибута элемента Python lxml - PullRequest
0 голосов
/ 28 февраля 2019

Мне нужно создать 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"

Я не могу получить : в атрибуте элемента command.

Может кто-нибудь помочь мне с этой проблемой?

Я использую 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>

1 Ответ

0 голосов
/ 01 марта 2019

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 пространства имен, включая xsi для http://www.w3.org/2001/XMLSchema-instance.

...