2017-03-20 50 views
0

我正在嘗試爲python2創建帶有lxml.etree模塊的xml。這將是一件容易的事,如果沒有要求,即輸出應該是這樣的:?創建彈簧:lxml中的beans root

<spring:beans xmlns="http://membrane-soa.org/proxies/1/" 
xmlns:spring="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 

http://membrane-soa.org/proxies/1/http://membrane-soa.org/schemas/proxies-1.xsd「>

任何建議,我怎麼能這樣做,所有我能做到這一刻是:

<ns0:beans xmlns:ns0="http://membrane-soa.org/proxies/1/"/> 

所以如何讓 「春天」,而不是 「NS0」

感謝

+1

[lxml的標籤名稱的可能的複製帶有「 :「](http://stackoverflow.com/questions/8432912/lxml-tag-name-with-a) –

回答

1

使用地圖申報命名空間和使用None專門爲默認命名空間的關鍵:

結果
from lxml import etree as ET 

nsmap = { None: "http://membrane-soa.org/proxies/1/", 
      "spring": "http://www.springframework.org/schema/beans", 
      "xsi": "http://www.w3.org/2001/XMLSchema-instance" } 
root = ET.Element("{%s}beans" % nsmap["spring"], nsmap=nsmap) 
root.set("{%s}schemaLocation" % nsmap["xsi"], 
     "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd") 

(後格式化)

<spring:beans 
    xmlns:spring="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://membrane-soa.org/proxies/1/" 
    spring:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" 
/>