SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2009
    Posts
    72
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    need help in converting json to xml

    hi evryone,

    I need help in converting json to xml............need a javascript librarry
    If not what is the alternative way of doing it?

  2. #2
    SitePoint Addict ArunB's Avatar
    Join Date
    Jun 2008
    Location
    Hyderabad
    Posts
    252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You need to create a XML Document Object or XML string is enough?

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2009
    Posts
    72
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks for the reply..........
    can you tell, how to create xml string?

  4. #4
    SitePoint Enthusiast
    Join Date
    Sep 2005
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by abhishek.c View Post
    hi evryone,

    I need help in converting json to xml............need a javascript librarry
    If not what is the alternative way of doing it?
    Here is a function that converts arbitrary JSON objects to XML:

    Code:
    /**
     * JSON to XML
     * @param {Object} JSON
     */
    json2Xml = function(json, node) {
     
     var root = false;
     if (!node) {
      node = document.createElement('root');
      root = true;
     }
     
     for (var x in json) {
      // ignore inherited properties
      if (json.hasOwnProperty(x)) {
      
       if (x == '#text') { // text
        node.appendChild(document.createTextNode(json[x]));
       } else  if (x == '@attributes') { // attributes
        for (var y in json[x]) {
         if (json[x].hasOwnProperty(y)) {
          node.setAttribute(y, json[x][y]);
         }
        }
       } else if (x == '#comment') { // comment
       // ignore
       
       } else { // elements
        if (json[x] instanceof Array) { // handle arrays
         for (var i = 0; i < json[x].length; i++) {
          node.appendChild(json2Xml(json[x][i], document.createElement(x)));
         }
        } else {
         node.appendChild(json2Xml(json[x], document.createElement(x)));
        }
       }
      }
     }
     
     if (root == true) {
      return this.textToXML(node.innerHTML);
     } else {
      return node;
     }
     
    };
    The process is documented here:
    http://onwebdevelopment.blogspot.com...l-to-json.html
    Fiji Web Design - Enterprise Web Design


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •