Welcome, guest | Sign In | My Account | Store | Cart

There are many ways to convert a specific XML dialect into JSON for easier consumption by Javascript code. This recipe works for some XML-based data, where the format is not really a document and html tags are used as field placeholders. You can use it as-is, but it is intended to serve as a starting point where you can plug your specific needs.

Python, 64 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from xml.parsers.expat import ParserCreate

class Xml2Json:
    LIST_TAGS = ['COMMANDS']
    
    def __init__(self, data = None):
        self._parser = ParserCreate()
        self._parser.StartElementHandler = self.start
        self._parser.EndElementHandler = self.end
        self._parser.CharacterDataHandler = self.data
        self.result = None
        if data:
            self.feed(data)
            self.close()
        
    def feed(self, data):
        self._stack = []
        self._data = ''
        self._parser.Parse(data, 0)

    def close(self):
        self._parser.Parse("", 1)
        del self._parser

    def start(self, tag, attrs):
        assert attrs == {}
        assert self._data.strip() == ''
        print "START", repr(tag)
        self._stack.append([tag])
        self._data = ''

    def end(self, tag):
        print "END", repr(tag)
        last_tag = self._stack.pop()
        assert last_tag[0] == tag
        if len(last_tag) == 1: #leaf
            data = self._data
        else:
            if tag not in Xml2Json.LIST_TAGS:
                # build a dict, repeating pairs get pushed into lists
                data = {}
                for k, v in last_tag[1:]:
                    if k not in data:
                        data[k] = v
                    else:
                        el = data[k]
                        if type(el) is not list:
                            data[k] = [el, v]
                        else:
                            el.append(v)
            else: #force into a list
                data = [{k:v} for k, v in last_tag[1:]]
        if self._stack:
            self._stack[-1].append((tag, data))
        else:
            self.result = {tag:data}
        self._data = ''

    def data(self, data):
        self._data = data


# >>> Xml2Json('<doc><tag><subtag>data</subtag><t>data1</t><t>data2</t></tag></doc>').result
# {u'doc': {u'tag': {u'subtag': u'data', u't': [u'data1', u'data2']}}}

3 comments

fal 11 years, 4 months ago  # | flag

Hello,

I tried to run the code with command : python Xml2Json.py

I got error:

File "Xml2Json.py", line 63

Xml2Json('<doc><tag><subtag>data</subtag><t>data1</t><t>data2</t></tag></doc>').result ^ SyntaxError: invalid syntax

Any one know how to use the code?

Thank you

Nikola (author) 11 years, 3 months ago  # | flag

The line starting with >>> is intended to demonstrate the usage of the class. I put it in a comment now so it doesn't break the python interpreter if you just download the file.

ayadi syrine 7 years, 10 months ago  # | flag

how can i parse an xml file using the xml2json function ?

Created by Nikola on Thu, 9 Dec 2010 (MIT)
Python recipes (4591)
Nikola's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks