Click here to Skip to main content
12,749,046 members (39,963 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

59.4K views
2.7K downloads
10 bookmarked
Posted 25 Feb 2008

xml to json

, 25 Feb 2008 MIT
Rate this:
Please Sign up or sign in to vote.
convert xml to json - faster, stronger and more comfortable

Introduction

In javascript world, if you had to work with xml-document, and you would be tired of many many methods of xml-node to get attribute or access child-nodes such as getElementsByTagName, hasChildNodes, or firstChild, lastChild and nextSibling etc, then JSON is there for you.

It sounds good if you can access node in xml-document or attributes, child nodes list of xml-node as well as access properties of an object.

So if you're working in this space, you probably need to convert an existing XML document into a JSON structure.<o:p />

<o:p />

<o:p />

Background

On the client-side, JSON comes with a native language-compliant data structure, with which it performs much better than corresponding DOM calls required for XML processing.

To get more details, you should read "JSON: The Fat-Free Alternative to XML"

Why did I write this

There are tons of xml-to-json converter and after I was googling, I got many ways to deal with this, but xml2json is one of the best ways (which is the most returned link by Google)<o:p />

it works great but when I used it in my xml data, it throws an error.<o:p />

Before paying my attention to the difference between those 2 xml files, I read its code and found that it doesn't work with true xml-document and xml-node, in fact, it works with strictly string which is in xml-format.<o:p />

More important, with the analyst string approach, it needs more if-then-else and more RegExp to work well with a variety of input, because, we can't guess how many kinds of input user will enter. Also, it disables the power of xml-document as it automatically checks syntax and detects input error.<o:p />

Additionally, with many RegExp and other methods to process a string such as replace, lastIndexOf, split etc, it will take more time to parse string in xml-format to json-format.<o:p />

so, I started writing my own method to convert form true xml-document into json object.

Wow, it's well done, then I made small comparison between my solution and xml2json. As I guess, xml2json takes more time to process big data, and there are some data input, which xml2json can't parse or detect where syntax of input-data is wrong.<o:p />

Using the code

In the attached code, I also use a Log, and Timer to get how long does the code take to parse from xml to json-object, and I created 4 xml data files to check speed, error no_end_tag, error end_space (there is 1 - or more space character in front of " >" character), and check CDATA handler.

Blocks of code should be set as style "Formatted" like this:

To parse an xml-document to json object, you just call MX.XML.ToJSON method. It have 2 arguments, the first is xml-document, and the second is an option, if the second arguments is "true", all child nodes of xmlDocument will be put into an array. In other case, all single node of xmlDocument will be treated as property

Example:

<?xml version="1.0"?>   
<PEOPLE>
   <PERSON ATTENDENCE="present">
       <FIRST_NAME>Sam</FIRST_NAME>
       <LAST_NAME>Edwards</LAST_NAME>
   </PERSON>
   <PERSON ATTENDENCE="absent">
       <FIRST_NAME>Sally</FIRST_NAME>
       <LAST_NAME>Jackson</LAST_NAME>
   </PERSON>   
</PEOPLE>

We call

var json = MX.XML.ToJSON(xmlDocument);

And we have

{
    PEOPLE :
    {
        $attribute : null,
        $value     : "",
        $count     : 1,
        PERSON     :
        [
            {
                $attribute : { ATTENDENCE : "present" },
                $value     : "",
                $count     : 2,    
                FIRST_NAME : 
                {
                    $attribute : null,
                    $value     : "Sam",
                    $count     : 0
                },
                LAST_NAME  : 
                {
                    $attribute : null,
                    $value     : "Edwards",
                    $count     : 0
                }
            },            
            {
                $attribute : { ATTENDENCE : "absent" },
                $value     : "",
                $count     : 2,    
                FIRST_NAME : 
                {
                    $attribute : null,
                    $value     : "Sally",
                    $count     : 0
                },
                LAST_NAME  : 
                {
                    $attribute : null,
                    $value     : "Jackson",
                    $count     : 0
                }
            }
        ]
    }
}

if xml-files contains an error (may be wrong structure), json will be

{
    $attribute : null,
    $value     : "",
    $count     : 1,
    parsererror:
    {
        $attribute : null,
        $value     : "error detail here",
        $count     : 0,    
        sourcetext :
        {
            $attribute : null,
            $value     : "information about sourcetext here",
            $count     : 0,
        }
    }
}

$attribute: if a xml-Node has attribute, those attributes will be put in $attribute, in other case, $attribute is null.

I use $attribute instead of parse those attributes into properties as other child-Nodes to easier when convert from json to xml, which is coming soon.

$count: the number of child objects

$value: if firstChild of xml-node is textnode,

There are many other converters out there

I guess there are many others converter out there which is written in JavaScript, so it is interesting if you know about other converters, please let me know.

License

This article, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

HoangKC
Web Developer
Vietnam Vietnam
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralWorks great! Pin
Jordan Neville22-Feb-11 14:37
memberJordan Neville22-Feb-11 14:37 
GeneralFat-free alternative? Looks the other way around Pin
nsimeonov4-Mar-08 1:07
membernsimeonov4-Mar-08 1:07 
GeneralRe: Fat-free alternative? Looks the other way around [modified] Pin
HoangKC4-Mar-08 6:38
memberHoangKC4-Mar-08 6:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170215.1 | Last Updated 25 Feb 2008
Article Copyright 2008 by HoangKC
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid