pythonxmlxml-builder

Adding a XML root attribute with hyphens in python XMLBuilder


I'm integrating with the google checkout api and all of their attributes include hyphens in their attribute values. So to create a request to charge an order I need to send an xml post that looks like:

<?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>

I'm having trouble building that xml with the attribute "google-order-number". The following code works if I want to create an empty node:

>>> 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" /> 

But If I try to child node for the amount using the documented way:

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

I get an error saying:

SyntaxError: keyword can't be an expression

I've also tried:

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

and I get a traceback in the XMLBuilder library saying

    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

Any Ideas how to use an attribute like that? I'm using the XMLBuilder library located at http://pypi.python.org/pypi/xmlbuilder


Solution

  • You can pass the attributes in a dictionary like this:

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