Skip to main content
gamedev.net
🔒 Locked

Storing Python in XML

Started by Penance 6 replies 1.2k views
Original Post
Penance
Penance
Short story is that I want to store snippets of Python code in XML. Kind of similar to how WoW GUI elements can store Lua snippets in their XML. My problem is that Python's syntax is indentation-based, so I get syntax errors depending on how nested/indented the containing XML element is. My naive approach is going to be counting the number of tabs preceding the first line of code and then remove that many tabs after each new line character. *ugh!* Just wondering if anyone had dealt with this before and knows of any good, general, solutions that might be better than what I'm thinking of.
Zahlman
Zahlman
Quote:
Original post by Penance
Short story is that I want to store snippets of Python code in XML. Kind of similar to how WoW GUI elements can store Lua snippets in their XML.


Are you going to pass them to Python eval() or exec or something? If so, why are you using XML, instead of just writing one big Python expression to describe a nested data structure?
Penance
Penance
I'm using IronPython as the scripting language for an XNA project.

The UI is customizable and stored in XML, and each UI element has events and inputs that are scripted.

ie:<Element> <Position x="" y="" z=""/>  <OnLoad>     ...python code...  </OnLoad></Element>
Kambiz
Kambiz
Another idea would be to have a separate file maybe with the same name as the XML file but different extension and just write the function names in the XML file.
 ui.xml                      | ui.py -----------------------------|--------------------------<Element>                    | ... <Position x="" y="" z=""/>  | def on_load():  <OnLoad>                   |    ...     on_load                 |    ...  </OnLoad>                  |    ...</Element>                   | ...
Penance
Penance
Good point, Kambiz. I actually do support that currently, I just thought it'd be nice for devs to be able to put little snippets directly in the XML.

I came up with a first attempt at a solution last night.

Basically I walk the string until I get the first non-whitespace character, then walk from that point backwards until I get the first newline character, counting any tabs I come across.

Then I build up a string with that many tabs and do a Replace(tabSequence, "") and Trim() the original string.

Won't handle all cases, but it's a start. I guess when everyone keeps getting syntax errors and bugging me about it all the time I'll just force them to use the separate code file method ;)
Kylotan
Kylotan
You might look at how existing Python template languages like Kid and Genshi do it.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.