簡體   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