2

is it possible to build an XML string from a Python structure (e.g. nested lists, dictionaries, etc.) or it is a non-sense question?

Is there any standard tool?

Thanks

3
  • these nested list of dictionary contains tags of value? Commented Dec 29, 2011 at 11:05
  • If you just want to save some Python objects, use pickle. Anything fully general for arbitary Python objects would end up very Python-specific so you might as well use pickle. If you want interop with some other language, you have to know which data formats (not just "XML" but the exact schema) you can support on the other ends as well, and you need to tell us so we can tell you which ones are supported by Python as well. Commented Dec 29, 2011 at 11:08
  • I need XML to save data for MS Project and I was looking for something better than raw string building. Commented Dec 29, 2011 at 13:58

2 Answers 2

4

There is no object-to-XML serialization in the standard library, but there is pyxser.

Sign up to request clarification or add additional context in comments.

Comments

3

If you need some custom format, you can use xml.etree.ElementTree to programatically generate such a format. For example:

from xml.etree import ElementTree

def dict2xml(d, parent=None):
    if parent is None:
        parent = ElementTree.Element('xml')

    for key, value in d.items():
        if isinstance(value, str):
            element = ElementTree.SubElement(parent, key)
            element.text = value
    elif isinstance(value, dict):
            element = ElementTree.SubElement(parent, key)
            dict2xml(value, element)
    elif isinstance(value, list):
            for text in value:
            element = ElementTree.SubElement(parent, key)
            element.text = str(text)
        else:
            raise TypeError('Unexpected value type: {0}'
                            .format(type(value)))


    return parent

d = {'a': 'a contents',
     'b': {'c': 'c contents',
           'd': 'd contents',
           },
     'e': range(3),
     }

print ElementTree.tostring(dict2xml(d))

Generates the following output:

<xml><a>a contents</a><b><c>c contents</c><d>d contents</d></b><e>0</e><e>1</e><e>2</e></xml>

2 Comments

I do not know much about XML, but I think that this solution suites my needs: is it quite general to be used also for future needs?
@Don Yes, you can expand it in the future, for example, to define attributes for tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.