簡體   English   中英

如何使用 lxml 將命名空間包含到 xml 文件中?

[英]How to include the namespaces into a xml file using lxml?

我正在使用 python 和 lxml 庫從頭開始創建一個新的 xml 文件。

<route xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.xxxx" version="1.1"
xmlns:stm="http://xxxx/1/0/0"
xsi:schemaLocation="http://xxxx/1/0/0 stm_extensions.xsd">

我需要將此命名空間信息作為路由標記的屬性包含在根標記中。

我無法將信息包含在根聲明中。

from lxml import etree
root = etree.Element("route",
    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance",
    xmlns = "http://www.xxxxx",
    version = "1.1",
    xmlns: stm = "http://xxxxx/1/0/0"
)

有一個 SyntaxError: invalid syntax

我怎樣才能做到這一點 ?

這是如何做到的:

from lxml import etree

attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
nsmap = {None: "http://www.xxxx",
         "stm": "http://xxxx/1/0/0",
         "xsi": "http://www.w3.org/2001/XMLSchema-instance"}

root = etree.Element("route", 
                     {attr_qname: "http://xxxx/1/0/0 stm_extensions.xsd"},
                     version="1.1", 
                     nsmap=nsmap)

print etree.tostring(root)

此代碼的輸出(已添加換行符以提高可讀性):

<route xmlns:stm="http://xxxx/1/0/0"
       xmlns="http://www.xxxx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xxxx/1/0/0 stm_extensions.xsd"
       version="1.1"/>

主要的“技巧”是使用QName創建xsi:schemaLocation屬性。 名稱中帶有冒號的屬性不能用作關鍵字參數的名稱。

我已經在nsmap添加了xsi前綴的聲明,但實際上可以省略它。 lxml 為一些眾所周知的命名空間 URI 定義了默認前綴,包括http://www.w3.org/2001/XMLSchema-instance xsi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM