Giter Site home page Giter Site logo

soldair / node-jsontoxml Goto Github PK

View Code? Open in Web Editor NEW
101.0 6.0 38.0 41 KB

this renders a simple javascript object structure into xml/html. js objects are easier to modify than strings so no need to parse a whole dom to reliably add a few elements. while this could support async callbacks it doesn't. if people need it i will be happy to add support.

License: MIT License

JavaScript 100.00%

node-jsontoxml's Introduction

Build Status

browser support

jsontoxml

This is a library designed to render js objects as xml. Its not made to parse or otherwise edit existing xml/html structures. For that and perhaps as a compliment to this you can use jsdom or xml2js for editing existing markup.

this will do a good job rendering json as xml but apis that require xml expect odd things mostly related to elements with attributes and implicit array like keys that make formatting your json a little tricky.

example

var jsonxml = require('jsontoxml');

var xml = jsonxml({
	node:'text content',
	parent:[
		{name:'taco',text:'beef taco',children:{salsa:'hot!'}},
		{name:'taco',text:'fish taco',attrs:{mood:'sad'},children:[
			{name:'salsa',text:'mild'},
			'hi',
			{name:'salsa',text:'weak',attrs:{type:2}}
		]},
		{name:'taco',attrs:'mood="party!"'}
	],
	parent2:{
		hi:'is a nice thing to say',
		node:'i am another not special child node',
		date:function(){
			return (new Date())+'';
		}
	}
})

console.log(xml);

outputs:

<node>text content</node>
<parent>
	<taco>
		beef taco
		<salsa>hot!</salsa>
	</taco>
	<taco mood='sad'>
		fish taco
		<salsa>mild</salsa>
		hi
		<salsa type="2">weak</salsa>
	</taco>
	<taco mood='party!'/>
</parent>
<parent2>
	<hi>is a nice thing to say</hi>
	<node>i am another not special child node</node>
	<date>Sun Sep 26 2010 17:27:29 GMT-0700 (PDT)</date>
</parent2>

API

jsontoxml (obj,options)

  • a valid json structure to interpret or a json string
  • returns an xml string
    • options is optional. it can be true (add generic xml header) or an object. If an object, valid options are:
      • escape
        • calls escape on all values
        • attribute values if attribute values are specified as an object
      • xmlHeader can either be boolan (add generic <?xml …?> header) or an object. If an object valid options are:
        • standalone if true, the <?xml …?> gets an additional attribute standalone="yes".
      • docType if defined gets added as the <!DOCTYPE …> contents (unescaped).
      • prettyPrint if truthy the output gets a rudimentary pretty print (good for debugging, don't expect too much)
      • indent specify what unit you would like to indent by (spaces, tabstop, nothing - pass an empty string)
      • removeIllegalNameCharacters replace illegal XML element Name characters with '_'
      • html instead of adding self closing tags for empty tags add an open and close tag. <salsa/> becomes <salsa></salsa>

jsontoxml.escape (string)

  • returns string with xml entities escaped
  • escapes "" & < >

jsontoxml.cdata (string)

  • wraps string with <![CDATA[ ]]>
  • removes all occurences of close cdata (]]>) in input text

more description

I made this because i wanted to abstract away the fact that antiquated external systems require post data as xml and i wanted to expose a standard js calling api like my other interfaces.

I did not want to instantiate an entire dom to perform simple updates to tags in lower level functions (like injecting api keys) when top level api call specific functions start building the xml string.

node-jsontoxml's People

Contributors

davidcalhoun avatar drewtunes avatar florianmientjes avatar jlank avatar joscha avatar ken-franken avatar musicsmithnz avatar soldair avatar yochannah avatar zacronos 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

node-jsontoxml's Issues

prettyPrint indents too much, spurious newlines may also break indentation

Debugging becomes tiresome with sloppy formatting.

The indentation level often seems to double-indent.

Newlines are thrown in at the end of nodes/loops, adding blank lines which break formatting.

These spurious newlines begin the next line with no indentation thus breaks formatting.

prettyPrint comment don't expect too much, well, either it prints pretty, or it doesn't, and it doesn't, so... either we fix, or maybe halfassedPrint would be a better name. ;)

Need help

How to write json to generate this xml. Esp. the SMS node.
"" +
"api" +
"777777" +
"default" +
"Get Perks" +
"91" +
"" +
"

" +
"" +
"" +
"";

Why is your module better than others js to xml converters?

I need to build a relatively simple XML document with some hierarchy and some attributes from a JS object. I stand now before choosing one of these modules:
https://github.com/davidcalhoun/jstoxml
https://github.com/soldair/node-jsontoxml
https://github.com/QuickenLoans/node-easyxml
https://github.com/michaelkourlas/node-js2xmlparser

Why should I pick this module instead of one of the others?

Disclaimer: I posted the same question as an issue on the other repositories too.

'name' attribute

Doing something like

app.packs.pack = name: pack.name, required: 'yes', preselected: 'yes', id: pack.name, file: {src: dirs.temp, targetdir: '$INSTALL_PATH', override: 'asktrue'}

jsxml.obj_to_xml(app) = <packs/>

when it should be more like <packs><pack name="whatever" blahblahblah /></packs>

I'm assuming it has something to do with the name attribute (since it's meant to be used elsewhere)

Handling array items

I need to convert the following json into xml:

{
    "content": [
        {
            "_id": "012345678901234567890123",
            "lastname": "Guénégo",
            "firstname": "Jean-Louis"
        },
        {
            "_id": "5ae5ef542523d439d8083335",
            "lastname": "Phengsiaroun",
            "firstname": "Dany",
            "__v": 0
        }
    ]
}

The output does not satisfy because it does not clearly sepearate the array items:

<content>
    <_id>012345678901234567890123</_id>
    <lastname>Guénégo</lastname>
    <firstname>Jean-Louis</firstname>
    <_id>5ae5ef542523d439d8083335</_id>
    <lastname>Phengsiaroun</lastname>
    <firstname>Dany</firstname>
    <__v>0</__v>
</content>

I would suggest to add in the options something like:
handleArrayElement: true

that would produce:

<content>
    <item>
        <_id>012345678901234567890123</_id>
        <lastname>Guénégo</lastname>
        <firstname>Jean-Louis</firstname>
    </item>
    <item>
        <_id>5ae5ef542523d439d8083335</_id>
        <lastname>Phengsiaroun</lastname>
        <firstname>Dany</firstname>
        <__v>0</__v>
    <item>
</content>

How to set in JSON tag with dash("-") ?

I have to get this format XML.
<batch-order xmlns="http://ws.plimus.com"> <shopper> <web-info> <ip>62.219.121.253</ip> <remote-host>www.merchant.com</remote-host>....
Problem is in tag names with dash. I cannot pass it in JSON, because it is not valid.

Thank you!

Change Encoding format on XML Header

Hello,

I have used option xmlHeader: true, which gives <?xml version="1.0" encoding="utf-8"?> on top of the XML.

However, I want to change "utf-8" to something else like "TIS-620", how do I do that? Thank you.

CDATA syntax

I believe the CDATA syntax is incorrect, according to the w3c standard it should begin with <![CDATA[ and end with ]]>. This library defines the opening part of CDATA as <!CDATA[[. If you agree I can whip up a tiny PR and fix it.

Buffer polyfill/shim

Hey Soldair,
First off, thanks for a nice module. I'd like to use it to convert json -> xml in a CouchDB show, unfortunately (or fortunately? depends), CouchDB uses spidermonkey to interpret and run javascript, thus there is no Buffer built in. The result of this, is that on line https://github.com/soldair/node-jsontoxml/blob/master/jsontoxml.js#L124 fails due to a ReferenceError:

ReferenceError(\"Buffer is not defined\"...

My patch proposal is simple, just do a check prior to the obj instanceof Buffer to see if this.Buffer exists, and if not, define a faux built in so the if statement doesn't blow up if it is running in an environment where there are no Buffers.

Thoughts?

Thanks.
JL

Typo in README example.

The line: node:'i am another not special child node' needs a comma after it, because it is broken syntax without it. Having a working example is handy.

empty strings are coming as self closing xml element

Hello,

at first thank you for that great library, I have a question: I am converting a small json object to xml but keys with empty strings values ("Value": "") in json are coming as self closing xml element (<Value />) But I want it to be a normal opening and closing xml element (<Value></Value>). What am I doing wrong ?

Code:

var myjson = { "Test_details": {
"Test_No.": {
"Value": "",
"Remark": "to be filled by me",
"Example": 1234
}}};

console.log(jsontoxml(myjson, xmlHeader=true, escape=true, removeIllegalNameCharacters=true));

Output:

<?xml version="1.0" encoding="utf-8"?>
<Test_details>
<Test_No.>
<Value />
<Remark>to be filled by me</Remark>
<Example>1234</Example>
</Test_No.>
</Test_details>

Add debug formatting

Great library! Simple, fast, and effective; thanks for sharing it.

One feature to consider: add an option to format the output for human reading and debugging (line returns, indentation, and so forth).

Cheers!

creating custom format

Hi,
I need help in creating structure in following manner.
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>url1</loc>
</sitemap>
<sitemap>
<loc>url2</loc>
</sitemap>
</sitemapindex>
Can u please help me out.

XML Conversion results in </>

Hello @soldair ,
at the moment I am having issues to convert a json string into xml.
It results in a string like this </></></>
I have added you to my Gitlab Repo. This contains the example where it results in this output.

check the variable output_group.

Would be great to find a reason why it does this.

Thankyou and Best Regards

Kaliph

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.