2012-11-08 22 views
0

我需要使用lxml的objectify模塊來創建一些xml元素,其中包含短劃線。例如:Python lxml objectify - 如何用短劃線創建元素

<program-id>$Id: myFile.py 3519 2012-07-17 13:37:20Z $</program-id> 
<formatter-txt>basic format</formatter-txt> 

我不能在網上有關如何在Python中做到這一點,當我嘗試做它找到的任何引用,這是一個語法錯誤。任何幫助,將不勝感激。

回答

2

使用文檔here,因爲我從來沒有使用客觀化:

>>> from lxml import objectify 
>>> doc = objectify.E.xml() 
>>> doc.append(getattr(objectify.E,'program-id')("$Id: myFile.py 3519 2012-07-17 13:37:20Z $")) 
>>> doc.append(getattr(objectify.E,'formatter-text')("basic format")) 
>>> from lxml import etree 
>>> print etree.tostring(doc,pretty_print=True) 
<xml xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <program-id py:pytype="str">$Id: myFile.py 3519 2012-07-17 13:37:20Z $</program-id> 
    <formatter-text py:pytype="str">basic format</formatter-text> 
</xml> 
+0

我知道這是不相關的,但你知道如何強制LXML輸出「」,而不是「」對於空元素? –

+0

@MikeDriscoll:我不確定這是可能的lxml和xml。在內容上它們是相同的。如果你確實需要它,我想可能有一種方法可以在''下使用文本佔位符或實體。例如。 ' |',然後在將它呈現爲字符串後,將它從xml中剝離出來。哈克。 – MattH

+0

下面是一個答案或多或少與你的空標記問題在這裏的評論相同的問題:http://stackoverflow.com/a/2771410/267781 – MattH