Code Monkey home page Code Monkey logo

x2js's Introduction

x2js - XML to JSON and vice versa for JavaScript

This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and has no any dependencies.

API functions

  • new X2JS() - to create your own instance to access all library functionality

  • new X2JS(config) - to create your own instance with additional config

  • <instance>.xml2json - Convert XML specified as DOM Object to JSON

  • <instance>.json2xml - Convert JSON to XML DOM Object

  • <instance>.xml_str2json - Convert XML specified as string to JSON

  • <instance>.json2xml_str - Convert JSON to XML string

  • <instance>.asArray - Utility function to work with a JSON field always in array form

  • <instance>.asDateTime - Utility function to convert the specified parameter from XML DateTime to JS Date

  • <instance>.asXmlDateTime - Utility function to convert the specified parameter to XML DateTime from JS Date or timestamp

Config options

  • escapeMode : true|false - Escaping XML characters. Default is true from v1.1.0+
  • attributePrefix : "<string>" - Prefix for XML attributes in JSon model. Default is "_"
  • arrayAccessForm : "none"|"property" - The array access form (none|property). Use this property if you want X2JS generates additional property _asArray to access in array form for any XML element. Default is none from v1.1.0+
  • emptyNodeForm : "text"|"object" - Handling empty nodes (text|object) mode. When X2JS found empty node like it will be transformed to test : '' for 'text' mode, or to Object for 'object' mode. Default is 'text'
  • enableToStringFunc : true|false - Enable/disable an auxiliary function in generated JSON objects to print text nodes with text/cdata. Default is true
  • arrayAccessFormPaths : [] - Array access paths - use this option to configure paths to XML elements always in "array form". You can configure beforehand paths to all your array elements based on XSD or your knowledge. Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*.child2/), or a custom function. Default is empty
  • skipEmptyTextNodesForObj : true|false - Skip empty text tags for nodes with children. Default is true.
  • stripWhitespaces : true|false - Strip whitespaces (trimming text nodes). Default is true.
  • datetimeAccessFormPaths : [] - DateTime access paths. Use this option to configure paths to XML elements for XML datetime elements. You can configure beforehand paths to all your datetime elements based on XSD or your knowledge. Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*.child2/), or a custom function. Default is empty.
  • useDoubleQuotes : true|false - Use double quotes for output XML formatting. Default is false.
  • xmlElementsFilter : [] - Filter incoming XML elements. You can pass a stringified path (like 'parent.child1.child2'), regexp or function
  • jsonPropertiesFilter : [] - Filter JSON properties for output XML. You can pass a stringified path (like 'parent.child1.child2'), regexp or function
  • keepCData : true|false - If this property defined as false and an XML element has only CData node it will be converted to text without additional property "__cdata". Default is false.

Online demo

JSFiddle at http://jsfiddle.net/abdmob/gkxucxrj/1/

Basic Usage

XML to JSON

// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
var jsonObj = x2js.xml_str2json( xmlText );

JSON to XML

// Create x2js instance with default config
var x2js = new X2JS();
var jsonObj = { 
     MyRoot : {
                test: 'success',
                test2 : { 
                    item : [ 'val1', 'val2' ]
                }
      }
};
var xmlAsStr = x2js.json2xml_str( jsonObj );

Working with arrays

Configure XML structure knowledge beforehand

    var x2js = new X2JS({
        arrayAccessFormPaths : [
           "MyArrays.test.item"
        ]
    });


    var xmlText = "<MyArrays>"+
        "<test><item>success</item><item>second</item></test>"+
        "</MyArrays>";
        
    var jsonObj = x2js.xml_str2json( xmlText );
    console.log(jsonObj.MyArrays.test2.item[0]);

Or using the utility function

    var x2js = new X2JS();
    var xmlText = "<MyArrays>"+
            "<test><item>success</item><item>second</item></test>"+
            "</MyArrays>";
    var jsonObj = x2js.xml_str2json( xmlText );
    console.log(x2js.asArray(jsonObj.MyArrays.test.item)[0]);

Working with XML attributes

Accessing to XML attributes

    // Create x2js instance with default config
    var x2js = new X2JS();   

    var xmlText = "<MyOperation myAttr='SuccessAttrValue'>MyText</MyOperation>";
    var jsonObj = x2js.xml_str2json( xmlText );

    // Access to attribute
    console.log(jsonObj.MyOperation._myAttr);

    // Access to text
    console.log(jsonObj.MyOperation.__text);
    // Or
    console.log(jsonObj.MyOperation.toString());

Configuring a custom prefix to attributes

    var x2js = new X2JS({
        attributePrefix : "$"
    });
    
    var xmlText = "<MyOperation myAttr='SuccessAttrValue'>MyText</MyOperation>";

    var jsonObj = x2js.xml_str2json( xmlText );

    // Access to attribute
    console.log(jsonObj.MyOperation.$myAttr);

Working with XML namespaces

Parsing XML with namespaces

    var xmlText = "<testns:MyOperation xmlns:testns='http://www.example.org'>"+
        "<test>Success</test><test2 myAttr='SuccessAttrValueTest2'>"+
        "<item>ddsfg</item><item>dsdgfdgfd</item><item2>testArrSize</item2></test2></testns:MyOperation>";

    var jsonObj = x2js.xml_str2json( xmlText );
    console.log(jsonObj.MyOperation.test);

Creating JSON (for XML) with namespaces (Option 1)

    var testObjC = {
            'm:TestAttrRoot' : {
                '_tns:m' : 'http://www.example.org',
                '_tns:cms' : 'http://www.example.org',
                MyChild : 'my_child_value',
                'cms:MyAnotherChild' : 'vdfd'
            }
    }
    
    var xmlDocStr = x2js.json2xml_str(
        testObjC
    );

Creating JSON (for XML) with namespaces (Option 2)

    // Parse JSON object constructed with another NS-style
    var testObjNew = {
            TestAttrRoot : {
                __prefix : 'm',
                '_tns:m' : 'http://www.example.org',
                '_tns:cms' : 'http://www.example.org',
                MyChild : 'my_child_value',
                MyAnotherChild : {
                        __prefix : 'cms',
                        __text : 'vdfd'
                }
            }
    }
    
    var xmlDocStr = x2js.json2xml_str(
        testObjNew
    );

Working with XML DateTime

Configuring it beforehand

    var x2js = new X2JS({
        datetimeAccessFormPaths : [
           "MyDts.testds" /* Configure it beforehand */
        ]
    });

    var xmlText = "<MyDts>"+
                "<testds>2002-10-10T12:00:00+04:00</testds>"+
        "</MyDts>";
    var jsonObj = x2js.xml_str2json( xmlText );

Or using the utility function

    var x2js = new X2JS();

    var xmlText = "<MyDts>"+
                "<testds>2002-10-10T12:00:00+04:00</testds>"+
        "</MyDts>";
    var jsonObj = x2js.xml_str2json( xmlText );

    console.log(x2js.asDateTime( jsonObj.MyDts.testds ));

Networking samples

Parsing AJAX XML response (JQuery sample)

    $.ajax({
        type: "GET",
        url: "/test",
        dataType: "xml",
        success: function(xmlDoc) {
            var x2js = new X2JS();
            var jsonObj = x2js.xml2json(xmlDoc);
      
        }
    });

Loading XML and converting to JSON

    function loadXMLDoc(dname) {
        if (window.XMLHttpRequest) {
            xhttp=new XMLHttpRequest();
        }
        else {
            xhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.open("GET",dname,false);
        xhttp.send();
        return xhttp.responseXML;
    }


    var xmlDoc = loadXMLDoc("test.xml");
    var x2js = new X2JS();
    var jsonObj = x2js.xml2json(xmlDoc);

x2js's People

Contributors

abdolence avatar vidakovic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

x2js's Issues

returning null while convert to JSON

Hi,
Thanks for x2js,

I am trying to convert the below XML content to JSON using "xml_str2json" but returning null.

<item> <category>Scarlett Johansson</category> <category>Movies</category> <category>Entertainment</category> <merlin:image orientation="landscape">omNMmo6Ony6</merlin:image> </item>

when I am removing <merlin:image... line it is working fine. So, tell what should I do to convert the above structure into JSON.

Bower name 'abdmob/x2js' causing issues

That bower name is causing bower to save the entry like this
capture

Which causes this error on bower install
capture

ECMDERR Failed to execute "git ls-remote --tags --heads abdmob/x2js=https://github.com/abdmob/x2js.git", exit code of #128 fatal: I don't handle protocol 'abdmob/x2js=https'

All because of the foward-slash... a rename could save other people some surprises.
like the one i got when my build failed on bower install

Ignore tags with a single attribute xsi:nil

I am trying to parse an XML where some elements have a single attribute xsi:nil="true" and no contents.

But it parses it to:
{ _xsi:nil: "true" }

Would it be possible to delete those elements?

Custom transformers

Is it possible to make lib supports plugins ?
For example, to register functions-transformers which would be called during parsing to transform values/keys/attributes ?

Text element order gets changed when doing "xml to json" and "json to xml"

x2js is great! But, facing the below issues... can you provide solution for it?

<tree>
    <node1> 
      textTextText 
      <subnode1> text1 </subnode1>
      <subnode2> text2 </subnode2>
    </node1>
</tree>

when doing xml to json

{
  "tree": {
    "node1": {
      "subnode1": "text1",
      "subnode2": "text2",
      "__text": "textTextText"
    }
  }
}
  1. And 'json to xml'
<tree>
	<node1>
		<subnode1>text1</subnode1>
		<subnode2>text2</subnode2>
                textTextText
        </node1>
</tree>

As you can see, the text nodes are pushed to last when reconverting.

Arrays natural translation possibility

Let's try the following XML:

<data>
    <totalrows>2</totalrows>
    <rows>
      <row>
          <prop1>A</prop1>
          <prop2>B</prop2>
          <prop3>C</prop3>
      </row>
      <row>
          <prop1>D</prop1>
          <prop2>E</prop2>
          <prop3>F</prop3>
      </row>
    </rows>
</data>

x2js converts it to this JSON:

{
  "data": {
    "totalrows": "2",
    "rows": {
      "row": [
        {
          "prop1": "A",
          "prop2": "B",
          "prop3": "C"
        },
        {
          "prop1": "D",
          "prop2": "E",
          "prop3": "F"
        }
      ]
    }
  }
}

Look at <rows> element. Basically it's a container for collection of <row> elements. In other words, <rows> should naturally be translated to "rows":[...], where each <row> should be an object (anonymous, because of javascript nature):

{
  "data": {
    "totalrows": "2",
    "rows": [
        {
          "prop1": "A",
          "prop2": "B",
          "prop3": "C"
        },
        {
          "prop1": "D",
          "prop2": "E",
          "prop3": "F"
        }
    ]
  }
}

But instead, x2js translates <rows> to an object with the only one property <row> which is array.

When I'm trying to use this config to translate <rows> to array:

{ arrayAccessFormPaths  : ["data.rows"] }

then I'm getting this result:

{
  "data": {
    "totalrows": "2",
    "rows": [
      {
        "row": [
          {
            "prop1": "A",
            "prop2": "B",
            "prop3": "C"
          },
          {
            "prop1": "D",
            "prop2": "E",
            "prop3": "F"
          }
        ]
      }
    ]
  }
}

which makes "rows" an array containing one object with (again) the only one "row" element which in turn is array of actual objects. And this doesn't make much sense.

Is there a way to get a natural array translation in x2js? If we care about array's elements names, it's possible to add an accessor to the array'ed object, like this:

          {
            __object_name: "row",
            "prop1": "A",
            "prop2": "B",
            "prop3": "C"
          }

Empty node exception

When an xml file contains an empty node, the parser returns an exception. The empty node that it can't handle is
<p />
I configured to X2JS to use emptyNodeForm : "text" but the parser is still returning an exception.

Git Tags for Bower

Hi,

Is it possible to provide a few Git tags that correspond to various versions of the library? It will enable us to use a specific version in bower as opposed to an empty one - "".

IE 11 parsing date text in xml into a json object instead of string

Hi,
I have this weird issue on parsing xml to json with our application integrated inside our clients app. Our client launched our app inside an iframe and they are getting an issue with date showing as NaN. X2JS parses 1979-09-25T00:00:00-05:00 as object with __text property and the value is 1979\n-\n09\n-\n25T00:00:00\n-\n05:00. And this is only happens in IE11 when our application is inside our clients app. But when we launched our application outside clients app (by putting the url directly to the browser) it is parsing as string dateOfBirth: "1979-09-25T00:00:00-05:00". Would somebody help us with this or any thought on why is this happening? Thank you.

Produces invalid XML element names

When converting from JSON to XML I get invalid XML element names such as <0> and that is not allowed. Perhaps they should be escaped in some way.

Example, this JSON:

   "deMag": [
      {
        "settings": {
          "generator": 1,
          "startCurrent": 5
        },
        "data": [ { } ]
      }
    ],

produce this XML:

    <deMag>
      <settings>
        <generator>1</generator>
        <startCurrent>5</startCurrent>
      </settings>
      <data>
        <$H>7535</$H>
      </data>
    </deMag>

Handle case of "i:nil="true" for the value being null.

A standard way of handling null in an XML is to do this:

<thing i:nil="true"></thing>

which translates to:

{ "thing": null }

This is different than just having an empty clause:

<thing></thing>

which translates to:

{ "thing":"" }

Configuration option jsonPropertiesFilter does not work

I was trying to remove a property from the output XML using jsonPropertiesFilter, but no matter what I put in the array, it removes all properties.

                var converter = new x2js({
                    // Escaping XML characters. Default is true from v1.1.0+
                    escapeMode: true,
                    // XML attributes prefix. Default is "_"
                    attributePrefix: "_",

                    // Array access form (none|property). 
                    // Use this property if you want X2JS generate additional property <element>_asArray 
                    // to access in array form any element
                    // Default is 'none' from v1.1.0+
                    arrayAccessForm: "none",

                    // Handling empty nodes (text|object). 
                    // When X2JS found empty node like <test></test> it will be transformed to test : '' for 'text' mode, 
                    // or to Object for 'object' mode  
                    // Default is 'text'
                    emptyNodeForm: "text",

                    // Enable/Disable auxiliary function in generated JSON object to print text nodes with __text/__cdata
                    // Default is true
                    enableToStringFunc: true,

                    // Array access paths (array). 
                    // Use this option to configure paths to XML elements always in "array form". 
                    // You can configure beforehand paths to all your array elements based on XSD or your knowledge
                    // about XML structure
                    // Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*\.child2/), or a custom function
                    // Default is empty array
                    arrayAccessFormPaths: [],
                    // Strip whitespaces (trimming text nodes)
                    stripWhitespaces: true,

                    // Skip empty text tags for nodes with children
                    skipEmptyTextNodesForObj: true,

                    // DateTime access paths (array). 
                    // Use this option to configure paths to XML elements for "datetimes form". 
                    // You can configure beforehand paths to all your array elements based on XSD or your knowledge
                    // about XML structure
                    // Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*\.child2/), or a custom function
                    // Default is empty array
                    datetimeAccessFormPaths: [],

                    jsonPropertiesFilter: ['TYPE_NAME']

                });

                var XMLstring = converter.json2xml_str(jObj);

xml_str2json gives syntax error on Firefox

I am using Firefox 43.0 and X2JS 1.2.0 on a current 64 bit Linux box. Everything works fine on Chrome. When I run the following code on Firefox it gives me a syntax error in the console of their debugger (F12):

var x2js = new X2JS();
var xmlText = "<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
var jsonObj = x2js.xml_str2json( xmlText );

I also get a syntax error when I run your similar fiddle. The line referenced is the first line of the html file. (which contains ). Not sure what to do.

Thanks!

Boolean values

Is it possible to convert boolean value in their string formats into actual true or false values, when converting from XML to JSON? We have a usecase where the string version of "true" does not fill in for actual true value.

always parse elements as objects with __text property

Hi, thanks for the great tool !
i have a question though..
having:
xml1 = '<root><tag>word</tag></root>'
and
xml2 = '<root><tag attr="1">word</tag></root>'
they transform to
{"root":{"tag":"word"}}
and
{"root":{"tag":{"_attr":"1","__text":"word"},}}
is there a way to tranform all tags to objects with __text property indipendently of presence of attributes?
So to keep consistency on json structure ..

Tested with config options, without success:
emptyNodeForm :"object"
skipEmptyTextNodesForObj : false
keepCData : true
enableToStringFunc : false

IE \n before Turkish chars in parseFromString

To prevent this,

I added the below code to parseXmlString func

// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
else {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlDocStr);
return xmlDoc;
}

requirejs loading not work

I added x2js on my bower.json file

"x2js": "~1.2.0"

Then add in my main.js requirejs config file

paths: {
'x2js': '../vendor/x2js/xml2json.min'
....
}

shim: {
   'x2js' : {
          exports : 'X2JS'
        },
....
   'admin-lte' : {
          deps: [
            'jquery', 
            'jquery.bootstrap', 
            'toastr', 
            'bootstrap-datepicker',
            'jquery.transform',
            'x2js'
          ]
        }
}

In my script

var x2js = new X2JS();
var json_obj = x2js.xml_str2json(xml_str);
console.log('module [json obj]: ', json_obj);

I've this error:

ReferenceError: X2JS is not defined

JSON keys in camel case.

I'd like to have a possibility to specify an options which would force the lib create keys in camel keys for JSON object. And back.

Can it be used in nodejs ?

Hi,

It's a very great tool,

I'm looking to use in node server, is it possible? for now I'm facing problem with window object error.

Could you help me with that ?

thanks a lot

json2xml_str not parsing single quotes and some other characters.

When trying to convert from a Json Object having single quotes, slashes, colons etc to xml, the output prints the ascii values instead of the symbols.

For Example:

Lets say a part of my Json Object looks some thing like this
"Object { value : " id='480' name='USEclipse' status='1'}"

Then the XML generated would have the values as
id=&#x27;480&#x27; name=&#x27USEclipse&#x27;

IE11 X2JS undefined

For some reason var x2js = new X2JS() is failing on IE, it keeps giving X2JS is undefined

I tried doing an ajax call to my API which returns a JSON and trying to convert it to XML, this is working okay on other browsers except IE 11.

This is what I'm trying to do.
$.get(apiUrlPath) .then(function (data) { var x2js = new X2JS(); var json2XMLResult = x2js.json2xml_str(data); console.log(data, json2XMLResult) })

Any ideas why its failing on IE11, although the jsfiddle example seems to be okay on IE.

I've put this in my index.html
<script src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>

attributePrefix cannot be empty string

Currently our project uses version 1.0.11, and we set attributePrefix to ''.

We are looking at upgrading to the latest version, but this will not allow attributePrefix to be an empty string since empty strings are falsy and therefore config.attributePrefix || "_" returns "_".

It would be great if x2js explicitly checked for undefined for this option rather than falsy-ness.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of abdmob/x2js!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library abdmob/x2js is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "abdmob/x2js",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Working with integers??

Is it possible to avoid getting "" in numeric values when converting XML to JSON

<xml><a>String</a><b>3</b></xml>
yeilds {"xml":{"a":"String","b":"3"}}

instead of
{"xml":{"a":"String","b":3}}

: and " in XML

Many thanks for sharing this greate library, but I have two problems:

  1. Problem
    If there's a : in the xml tag, I get the followin error:
    Uncaught TypeError: Cannot read property 'Subscription' of null
    at xmltojson (Own.html:22)
    at onload (Own.html:42)
    XML content is the following:
    "ns:2flagsnu</ns:2flags>"

  2. Problem
    If there's a " instead of a ' I get the following error:
    Uncaught SyntaxError: Unexpected number
    XML content is the following:
    ""

Is there a way to fix this?

Node ReferenceError: X2JS is not defined ??

Hi, not sure if I'm doing something wrong here but I'm getting the following issue "ReferenceError: X2JS is not defined". Any help would be greatly appreciated.

Thanks

server:test chris$ cat package.json
{
"name" : "myapp",
"version" : "0.0.1",
"main" : "main.js",
"dependencies": {
"x2js": "^3.1.0"
}
}

server:test chris$ npm install x2js
[email protected] /Users/chris/scripts/tapps_proj/test
└── [email protected]

npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.
server:test chris$ node main.js
/Users/chris/scripts/tapps_proj/test/main.js:4
var x2js = new X2JS();
^

ReferenceError: X2JS is not defined
at Object. (/Users/chris/scripts/tapps_proj/test/main.js:4:16)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server:test chris$ cat main.js
require('x2js');

// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "Successval1val2";
var jsonObj = x2js.xml_str2json( xmlText );

IE11 and Edge throw XML5602: Unexpected end of input whenever parsing valid xml

When trying to figure out the parsererrorNS by parsing the 'INVALID' string IE11 and Edge actually log an error within the parseXMLString function.

Is there any reason to use the parsererrorNS to see whether a parsed xmlDoc contains an error as opposed to just looking for the parsererror tag directly?

I would think doing xmlDoc.getElementsByTagName("parsererror").length > 0 should work to figure out whether there was an error with no need for the namespace

Pretty print XML produced with x2js

I'm using x2js.json2xml_str() to generate XML files from JSON. This call outputs an unindented string that is unreadably by humans. It would be great to be able to pretty print resulted XMLs. I've briefly looked into the code of x2js but couldn't find anything helpful.
Is pretty printing currently supported?

Escaping control characters in attributes

You might want to add escaping/unescaping for invisible control character, which I ran into:

...
        function escapeXmlChars(str) {
            if (typeof str === "string") {
                return str.replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#x27;')
                    .replace(/\//g, '&#x2F;')
                    .replace(/\r/g, '&#xD;')
                    .replace(/\n/g, '&#xA;')
                    .replace(/\t/, '&#x9;')
                    .replace(/ /, '&#x20;');
            }
            return str;
        }

        function unescapeXmlChars(str) {
            return str.replace(/&amp;/g, '&')
                .replace(/&lt;/g, '<')
                .replace(/&gt;/g, '>')
                .replace(/&quot;/g, '"')
                .replace(/&#x27;/g, "'")
                .replace(/&#x2F;/g, '\/')
                .replace(/&#xD;/, '\r')
                .replace(/&#xA;/, '\n')
                .replace(/&#x9;/, '\t')
                .replace(/&#x20;/, ' ');
        }
...

add to npm

I tried to find there, an aparently there are some forks with the same name published.

"module is not defined"

I'm trying to use this library in Zotero standalone (4.0.29), which is based on Firefox 48 which I think should support most of ECMAScript 6... however I get an error "module is not defined". Seems like there's something up with the environment, but the library description says there are no dependencies.

How to generate xml while keeping the order.

Hi

I can't find the way/format of the JSON object for generating the following XML (with the same order)

<parent>
   <id>a</id>
   <value>aa</value>
   <id>b</id>
   <value>bb</value>
</parent>

The order of the tags is crucial for me.
If you will try the above xml in the jsfiddle test page you will notice that after pressing the XML -> JSON and JSON -> XML the original XML will be replaced by a new with different order of the nodes (which is bad for me).

Any ideas?

x2js.json2xml_str not close the element with full tag

Hi,
I used the function json2xml_str which get a json object and returned xml string
This function return the xml not with full closing tag :
''
instead of:
''

It is make me problems,
how can I get the xml string with full closing tags?

Thanks,
Reizy

Invalid 'name' in package.json

Hi guys.

I've tried to install your library using npm but get the following issue:

$ npm install git+https://github.com/abdmob/x2js.git --save
npm ERR! addLocal Could not install /tmp/npm-6604-622e8ec5/git-cache-30c70c4a6eeb/41782e9b53e2c4093873ea8d761805ae1935d753
npm ERR! Linux 3.19.0-39-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "git+https://github.com/abdmob/x2js.git" "--save"
npm ERR! node v4.2.4
npm ERR! npm  v2.14.12

npm ERR! Invalid name: "abdmob/x2js"
npm ERR! 
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

I think you need to remove the forwardslash from the package name in package.json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.