在python XMLBuilder中添加带连字符的XML根属性

时间:2011-08-13 22:27:34

标签: python xml xml-builder

我正在与Google Checkout api集成,其所有属性在其属性值中都包含连字符。因此,要创建一个订单收费请求,我需要发送一个看起来像这样的xml帖子:

<?xml version="1.0" encoding="UTF-8"?>
<charge-and-ship-order xmlns="http://checkout.google.com/schema/2" google-order-number="6014423719">
    <amount currency="USD">335.55</amount>
</charge-and-ship-order>

我在使用属性“google-order-number”构建该xml时遇到问题。如果我想创建一个空节点,则以下代码有效:

>>> xml=XMLBuilder()
>>> xml << ('charge-and-ship-order, {'xmlns':'xxx','google-order-number':'3433'})
>>> str(xml)
>>> <charge-and-ship-order google-order-number="3433" xmlns="xxx" /> 

但是如果我使用记录的方式尝试子节点的数量:

>>> xml=XMLBuilder()
>>> with xml('charge-and-ship-order', xmlns='xxx', google-order-number='3433'}):
>>>     with xml('amount', currency="USD"):
>>>         xml << '4.54'

我收到错误说:

SyntaxError: keyword can't be an expression

我也试过了:

>>> xml=XMLBuilder()
>>> with xml('charge-and-ship-order', {'xmlns':'xxx', 'google-order-number':'3433'}):
>>>     with xml << 'test'

我在XMLBuilder库中得到一个回溯说

    File "/xmlbuilder/xmlbuilder/__init__.py", line 102, in __call__
    x(*dt,**mp)
    File "/xmlbuilder/xmlbuilder/__init__.py", line 36, in __call__
    text = "".join(dt)
    TypeError: sequence item 0: expected string, dict found

任何想法如何使用这样的属性?我正在使用位于的XMLBuilder库 http://pypi.python.org/pypi/xmlbuilder

1 个答案:

答案 0 :(得分:0)

您可以在字典中传递属性,如下所示:

function_call(**{'weird-named-key': 'value'})