python - lxml 中的命名空间
问题描述
我想用lxml
包创建以下 XML:
<configuration xmlns:cond="http://www.aaa.com/orc/condition" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../schema/variation-config.xsd">
<strategy id="XXX">
<conditions>
<cond:scenario>A</cond:scenario>
</conditions>
</strategy>
</configuration>
到目前为止,我有以下代码,完全不能令人满意:
XHTML_NAMESPACE = "http://www.aaa.com/orc/condition"
XHTML = "{%s}" % XHTML_NAMESPACE
NSMAP = {
'cond' : XHTML_NAMESPACE,
'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
}
root = etree.Element(
"configuration",
nsmap=NSMAP,
)
strategy = etree.SubElement(root, "strategy", id="XXX")
conditions = etree.SubElement(strategy, "conditions")
cond1 = etree.SubElement(conditions, XHTML + "scenario", nsmap=NSMAP)
cond1.text = "A"
它给了我:
<configuration xmlns:cond="http://www.aaa.com/orc/condition" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<strategy id="XXX">
<conditions>
<cond:scenario>A</cond:scenario>
</conditions>
</strategy>
</configuration>
问题:
我只是想念xsi:noNamespaceSchemaLocation="../schema/variation-config.xsd"
. 你知道我如何将它添加到 XML 中吗?
解决方案
用更好的解决方案更新问题后,我认为您缺少为现有元素设置属性的方法。使用set
方法:
root.set(XSI + "noNamespaceSchemaLocation", "../schema/variation-config.xsd")
此外,当您将子元素添加到已经知道 中定义的命名空间的元素时,nsmap
无需nsmap
再次包含。换句话说,而不是
cond1 = etree.SubElement(conditions, XHTML + "scenario", nsmap=NSMAP)
你可以写
cond1 = etree.SubElement(conditions, XHTML + "scenario")
最后,XHTML
是一个不幸的变量名,因为 XHTML 是一个标准名称空间。
产生正确结果的解决方案
from lxml import etree
COND_NAMESPACE = "http://www.aaa.com/orc/condition"
XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"
COND = "{%s}" % COND_NAMESPACE
XSI = "{%s}" % XSI_NAMESPACE
nsmap = {"cond": "http://www.aaa.com/orc/condition", "xsi": "http://www.w3.org/2001/XMLSchema-instance"}
root = etree.Element("configuration", nsmap=nsmap)
root.set(XSI + "noNamespaceSchemaLocation", "../schema/variation-config.xsd")
strategy = etree.SubElement(root, "strategy", id="XXX")
conditions = etree.SubElement(strategy, "conditions")
scenario = etree.SubElement(conditions, COND + "scenario")
scenario.text = "A"
print(etree.tostring(root, pretty_print=True))
输出
<configuration xmlns:cond="http://www.aaa.com/orc/condition" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../schema/variation-config.xsd">
<strategy id="XXX">
<conditions>
<cond:scenario>A</cond:scenario>
</conditions>
</strategy>
</configuration>
推荐阅读
- amazon-sagemaker - 使用自定义模型在 AWS Sagemaker 中运行烧瓶应用程序
- chat - Azure 通信服务聊天在 azure 应用程序中不起作用
- mongodb - 在 MongoDB 查找聚合中使用管道时获取空数组
- bash - 从第二个字符读取直到第一次出现分隔符
- php - 服务器是否一直调用“isset”?
- apache-spark - 使用 DBSCAN for PySpark 检测异常值的问题
- terraform - 可选元素的动态块
- python - 删除具有连续索引和 ID 的串联数据框中的一行
- mongodb - 如何使用pyspark从databricks集群连接到mongodb Atlas
- c++ - 检查变量在堆内存中的分配方式(用于调试运行时错误)