python - python lxml元素属性问题
问题描述
我必须构建一个如下所示的 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>
除了命令属性外,我一切正常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 定义了默认前缀,包括xsi
for http://www.w3.org/2001/XMLSchema-instance
.
推荐阅读
- c++ - 如何使用 ifstream 获取文件中的最新更改?
- r - 平均R中的不同列
- sql - SQL:您如何计算设施的占用率/使用中的数量?
- arrays - 为什么我不能迭代在 C 中返回的字符串?
- javascript - 如何将 Ajax 请求发送到同一服务器的不同 url
- java - 如何在android studio中保存seekbar值?
- opencv - 如何修复 gocv 上的 GLCM 调用
- linq - 无法使用 marten 和 Linq 查询子类型
- google-chrome - 编写用于触发 chrome 快捷方式的 Chrome 扩展程序
- python - 循环遍历列名称熊猫的错误