lxml中的命名空间

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

我想用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吗?

python xml lxml
1个回答
0
投票

用更好的解决方案更新问题后,我认为您缺少为现有元素设置属性的方法。使用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>
© www.soinside.com 2019 - 2024. All rights reserved.