GithubHelp home page GithubHelp logo

summersremote / xmltojson Goto Github PK

View Code? Open in Web Editor NEW
251.0 13.0 132.0 147 KB

simple javascript utility for converting xml into json

License: MIT License

JavaScript 92.84% HTML 1.29% CSS 5.88%

xmltojson's Introduction

xmlToJSON

A simple javascript module for converting XML into JSON within the browser.

Features

  • no external dependencies
  • small (~3kb minified)
  • simple parsing. pass either a string or xml node and get back a javascipt object ( use JSON.stringify(obj) to get the string representation )
  • supports atrributes, text, cdata, namespaces, default namespaces, attributes with namespaces... you get the idea
  • lots of rendering of options
  • consistent, predictable output
  • browser support - it works on IE 9+, and nearly every version of Chrome, Safari, and Firefox as well as iOS, Android, and Blackberry. (xmlToJSON will work for IE 7/8 as well if you set the xmlns option to false)

Parsing XML (esp. with namespaces) with javascript remains one of the great frustrations of writing web applications. Most methods are limited by such things as poor browser support, poor or non-existent namespace support, poor attribute handling, incomplete representation, and bloated dependencies.

xmlToJSON may not solve all of your woes, but it solved some of mine :)

Usage

Include the src

<script type="text/javascript" src="path/xmlToJSON.js"></script>

and enjoy! xmlToJSON is packaged as a simple module, so use it like this

 testString = '<xml><a>It Works!</a></xml>';  	// get some xml (string or document/node)
 result = xmlToJSON.parseString(testString);	// parse

The (prettified) result of the above code is

{
   "xml": {
       "a": [
           {
               "text": "It Works!"
           }
       ]
   }
}

Node Usage

While this library does not officialy support use in the NodeJS environment; several users have reported good results by requiring the xmldom package.

User sethb0 has suggested the following workaround example.

const { DOMParser } = require('xmldom');
const xmlToJSON = require('xmlToJSON');
xmlToJSON.stringToXML = (string) => new DOMParser().parseFromString(string, 'text/xml');

Options

// These are the option defaults
var options = { 
	mergeCDATA: true,	// extract cdata and merge with text nodes
	grokAttr: true,		// convert truthy attributes to boolean, etc
	grokText: true,		// convert truthy text/attr to boolean, etc
	normalize: true,	// collapse multiple spaces to single space
	xmlns: true, 		// include namespaces as attributes in output
	namespaceKey: '_ns', 	// tag name for namespace objects
	textKey: '_text', 	// tag name for text nodes
	valueKey: '_value', 	// tag name for attribute values
	attrKey: '_attr', 	// tag for attr groups
	cdataKey: '_cdata',	// tag for cdata nodes (ignored if mergeCDATA is true)
	attrsAsObject: true, 	// if false, key is used as prefix to name, set prefix to '' to merge children and attrs.
	stripAttrPrefix: true, 	// remove namespace prefixes from attributes
	stripElemPrefix: true, 	// for elements of same name in diff namespaces, you can enable namespaces and access the nskey property
	childrenAsArray: true 	// force children into arrays
};	

// you can change the defaults by passing the parser an options object of your own
var myOptions = {
	mergeCDATA: false,
	xmlns: false,
	attrsAsObject: false
}

result = xmlToJSON.parseString(xmlString, myOptions);

A more complicated example (with xmlns: true)

<?xml version="1.0" encoding="UTF-8"?>
<xml xmlns="http://default.namespace.uri">
    <a>
        <b id="1">one</b>
        <b id="2"><![CDATA[some <cdata>]]>two</b>
        <ns:c xmlns:ns="http://another.namespace" ns:id="3">three</ns:c>
    </a>
</xml>

results in

{
        "xml": [{
                "attr": {
                        "xmlns": {
                                "value": "http://default.namespace.uri"
                        }
                },
                "a": [{
                        "b": [{
                                "attr": {
                                        "id": {
                                                "value": 1
                                        }
                                },
                                "text": "one"
                        }, {
                                "attr": {
                                        "id": {
                                                "value": 2
                                        }
                                },
                                "text": "some <cdata>two"
                        }],
                        "c": [{
                                "attr": {
                                        "xmlns:ns": {
                                                "value": "http://another.namespace"
                                        },
                                        "id": {
                                                "value": 3
                                        }
                                },
                                "text": "three"
                        }]
                }]
        }]
}

xmltojson's People

Contributors

billautomata avatar julkue avatar metatribal avatar nasangw avatar rnons avatar summersremote 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

xmltojson's Issues

Error parsing xml

Hi,

I am trying to use your xmltojson converter and cannot seem to get it to work.

I am trying to use this npm module as part of a nativescript application that does not have a DOM. I have noticed that the stringToXML function only caters for DOM and Microsoft ActiveXObject and returns a null value.

I am testing this code directly in node.

var xmlc= require('xmltojson');
var testString = 'It Works!'; // get some xml (string or document/node)
var myOptions = {
mergeCDATA: false,
xmlns: false
};
var result = xmlc.parseString(testString,myOptions);
console.log('xmlToJSON=' + result);
/*

and get the following errors:

var result = xmlc.parseString(testString,myOptions);
^
TypeError: Object # has no method 'parseString'
at Object. (I:\Software\nodejs\test\test.js:21:20)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

any ideas?

many thanks

Peter

Internal state (options) can be modified asynchronously

xmlToJSON uses single instance for every call, and every call modifies options object at parseXML function. Is it better to create onetime local copy of options for every call? Like this:

--- xmlToJSON.js-orig   2016-08-17 09:50:51.310936170 +0700
+++ xmlToJSON.js        2016-08-17 09:59:52.543327593 +0700
@@ -57,14 +57,16 @@
     };

     this.parseString = function(xmlString, opt) {
-        return this.parseXML(this.stringToXML(xmlString), opt);
+        var localoptions = {}
+        opt = opt || {}
+            // initialize options
+        for (var key in options) {
+            localoptions[key] = (opt[key] === undefined) ? options[key] : opt[key];
+        }
+        return this.parseXML(this.stringToXML(xmlString), localoptions);
     }

-    this.parseXML = function(oXMLParent, opt) {
-        // initialize options
-        for (var key in opt) {
-            options[key] = opt[key];
-        }
+    this.parseXML = function(oXMLParent, options) {
         var vResult = {},
             nLength = 0,
             sCollectedTxt = "";
@@ -154,7 +156,7 @@
                         sProp = oNode.nodeName;
                     }

-                    vContent = xmlToJSON.parseXML(oNode);
+                    vContent = xmlToJSON.parseXML(oNode, options);
                     if (!vResult['_children']) vResult._children = [];
                     vResult._children.push(vContent);
                     vContent._tagname = sProp;

Please publish new version, for JSPM compatibility

It appears that the very most recent commit of this project is compatible with JSPM, but all previous versions are not. Therefore, the following fails:

jspm install github:metatribal/xmlToJSON

(Or rather, the command works, but the module cannot be loaded)

But this succeeds:

jspm install github:metatribal/xmlToJSON@master

Therefore, please "version" the project again so that this latest commit is published as a version. That will make it "just work" without having to know anything about the above.

(On a broader note, it's a new world out there! Until the last few years, nearly everyone was just bringing libraries in with a script tag. Now there is a rapidly increasing expectation that module loaders will work, whether it is browserify with require, JSPM, etc. It is a bunch of stuff to get used to, but the development experience is vastly improved for large complex applications.)

How to force to dispaly 0 after decimal?

I have response which is in an xml file. When I am using this parser and converting json for some attributes which has value like '2.0' or '5.0' it is giving me simply '2' and '5'. How I can force it to give me '2.0' and '5.0'.

Cannot get it working with latest angular-cli with webpack

following directions given here: [http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html].
I did the following:
npm install xmltojson --save
npm install @types/xmltojson --save-dev

Then in app.component.ts add this line:
import * as xmltojson from 'xmltojson'

Yet xmltojson is not initialized correctly.
Comes back as empty javascript object

Update module on npm

Hello,

is it possible to make this available on npm again with the newest version? Newest npm version currently is 1.1.0, which is kind of outdated.

Thanks in Advance,
Simon

Cannot iterate children at proper order

Nodes order is important sometimes. I think, it is need to add _children array for proper order iterating, something like this:

--- xmlToJSON.js-orig   2016-05-05 13:37:23.096356807 +0700
+++ xmlToJSON.js        2016-05-05 17:39:14.599282243 +0700
@@ -156,7 +156,9 @@
                     }

                     vContent = xmlToJSON.parseXML(oNode);
-
+                    if(!vResult['_children']) vResult._children=[];
+                    vResult._children.push(vContent);
+                    vContent._tagname = sProp;
                     if (vResult.hasOwnProperty(sProp)) {
                         if (vResult[sProp].constructor !== Array) {
                             vResult[sProp] = [vResult[sProp]];

PS Sorry for my english

tag names in JSON result

Hi everyone.
My result for the test xml provided in Readme.md <xml><a>It Works!</a></xml> is {"xml":[{"a":[{"_text":"It Works!"}]}]}
Is there any option to remove the _text attribute that i'm not seeing? Has anyone encountered this before??
Thanks!

Different parsing in IE8 vs. Firefox v34.05

In Firefox, the head from my XML document will be parsed like this:

        "xmlns:xsi": {
          "_value": "http://www.w3.org/2001/XMLSchema-instance",
          "_ns": "http://www.w3.org/2000/xmlns/"
        },

in IE8 the head from the XML document will be parsed like this:

      "_attr": {
        "xmlns:xsi": {"_value": "http://www.w3.org/2001/XMLSchema-instance"},

It is not important for me to have the _ns attribute, but imho the parsing should be the same in all browsers!

NPM Update

Hey, could you do an npm publish with the latest version, it would be much appreciated.

Doesn't work in NodeJS

While README says the library has no external dependencies, it actually depends on global window object and DOMParser or ActiveXObject classes. Thus, the library cannot be used in NodeJS. @MetaTribal, please, mention this in README.

Support node v20.13.1 or latest

Hello,

This library creates incompatibility problem in Nodejs >=18 versions. Can integration be made to work in new Nodejs versions to solve this situation?

problem invoking "parseString" function

Hi,

I'm trying to use your library to convert an XML I get with ajax in a WEB-development.

The browser finds the js file on the server, but when I'm going to use the xmlToJSON.parseString, it's says it's not a function.

Looking the js file of the library, I think the function it's not been applied o added to the xmlToJSON object.
screenshot - 04042014 - 09 09 35 am

Version miss match

In bower.json, the version is 1.1. In the JS code, the version is 1.3.
It causes "Invalid Version" error when using bower to install from the GIT repository.

Migrate to DOM4

  • Need to verify against deprecated/moved functionality.
  • Consider impact on headless support (use in Node.js)

Add license in bower.json and .min.js

A license is necessary for third party services like versioneye.
Please also add your license to the .min.js file.

IMPORTANT: Release a new bower version after that. Otherwise nothing will change.

Cannot parse Android Manifest XML

Tried parsing the following XML:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.vending" platformBuildVersionCode="26" platformBuildVersionName="8.0.0">
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
    <uses-feature android:glEsVersion="0x00020000"/>
    <application android:allowBackup="true" android:alwaysRetainTaskState="true" android:anyDensity="true" android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:largeHeap="true" android:launchMode="singleInstance" android:name="com.android.vending.LiveApplication" android:normalScreens="true" android:persistent="false" android:screenOrientation="portrait" android:supportsRtl="true" android:theme="@style/AppTheme">
        <meta-data android:name="APPKEY" android:value="10505945"/>
        <receiver android:exported="true" android:name="com.google.android.gms.gcm.GcmReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
                <category android:name="gcm.play.android.samples.com.gcmquickstart"/>
            </intent-filter>
        </receiver>
        <service android:exported="false" android:name="com.gcm.MyGcmListenerService">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            </intent-filter>
        </service>
        <service android:exported="false" android:name="com.gcm.MyInstanceIDListenerService">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>
        <activity android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:launchMode="singleTop" android:name="com.linecorp.linesdk.auth.internal.LineAuthenticationActivity" android:theme="@style/LineSdk_AuthenticationActivity"/>
        <activity android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:name="com.android.vending.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="lineauth"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Got this error:

node_modules/xmltojson/lib/xmlToJSON.js:74
if (options.xmlns && oXMLParent.namespaceURI) {
^

TypeError: Cannot read property 'namespaceURI' of null
at Object.xmlToJSON.parseXML (node_modules/xmltojson/lib/xmlToJSON.js:74:41)
at Object.xmlToJSON.parseString (node_modules/xmltojson/lib/xmlToJSON.js:59:21)

Am I doing something wrong?

Question: Difference between textKey and valueKey?

While working with the plugin two questions came up which aren't answered in the documentation:

  • Why there are two different key names for text and value?
  • When the plugin will use textKey and when valueKey?

Parse boolean bug

With the groktext option set to true, while parsing an XML, 'false' values are returned as empty strings in JSON.

In xmltojson.js it looks like line 186 is where the problem happens. When a false value is encountered the groktype function returns a boolean false resulting in 'if (value)' to be false and then an empty string is returned instead of the boolean value, false.

How to convert XML to JSON in an external reference

why doesn't working this code?

test.xml

<xml><a>It Works!</a></xml>

html code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script src="js/xmltojson.js"></script>
</head>

<body>
    <script>
        $.ajax({
            url:'test.xml',
            type:'GET',
            datatype:'xml',
            success:function(data){
                console.log(data)
                testString = data;
                result = xmlToJSON.parseString(testString); // parse
                console.log(result)
            },
            error:function(){
                console.log('error')
            }
        })
        
    </script>
</body>

</html>

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.