2012-11-08 20 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