繁体   English   中英

lxml 中的命名空间

[英]Namespaces in 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM