首页 > 解决方案 > 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 中吗?

标签: pythonxmllxml

解决方案


用更好的解决方案更新问题后,我认为您缺少为现有元素设置属性的方法。使用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>

推荐阅读