• Stars
    star
    168
  • Rank 225,507 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript object to XML converter (useful for RSS, podcasts, GPX, AMP, etc)

jstoxml

npm downloads

Convert JavaScript objects (and JSON) to XML (for RSS, Podcasts, etc.)

Everyone loves JSON, and more and more folks want to move that direction, but we still need things outputted in XML! Particularly for RSS feeds and Podcasts.

This is inspired by node-jsontoxml, which was found to be a bit too rough around the edges. jstoxml attempts to fix that by being more flexible.

Installation

  • npm install jstoxml

Simple example

import { toXML } from 'jstoxml';

// toXML(content, config)
const content = {
    a: {
        foo: 'bar'
    }
};
const config = {
    indent: '    '
};

toXML(content, config);
/*
Output:
`<a>
    <foo>bar</foo>
</a>`
*/

Configuration object options (passed as second parameter to toXML())

Key name Type Default Description
indent string Indent string, repeated n times (where n=tree depth).
header string, boolean Outputs a simple XML 1.0 UTF-8 header when true. Can also be set to a custom string.
attributeReplacements object { "<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;" } XML attribute value substrings to replace (e.g. <a attributeKey="attributeValue" />). Does not double encode HTML entities (e.g. &lt; is preserved and NOT converted to &amp;lt).
attributeFilter function Filters out attributes based on user-supplied function.
attributeExplicitTrue boolean false When true explicitly outputs true attribute value strings, e.g. <a foo='true' /> instead of <a foo />.
contentMap function Custom map function to transform XML content. Runs after contentReplacements.
contentReplacements object { "<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;" } XML content strings to replace (e.g. <a>This & that</a> becomes <a>This &amp; that</a>).
selfCloseTags boolean true Whether tags should be self-closing.

Changelog

Version 3.2.0

  • new config option selfCloseTags added which is used as an easier global setting to enable/disable self-closing tags.

Version 3.1.0

  • config option contentMap can now be passed to transform any XML content. For instance, if you want <a>null</a> to instead appear as <a></a> you pass in contentMap: (content) => { return content === null ? '' : content }
  • fixed an issue with improper line breaks and indenting with null content

Version 3.0.0

  • BREAKING CHANGE: config option attributesFilter has been renamed attributeReplacements
  • BREAKING CHANGE: config option filter has been renamed contentReplacements
  • CDATA blocks are now untouched (no HTML entity replacements) and unindented (#56)
  • true attribute values can now be outputted by setting config option attributeExplicitTrue: true (#57)
  • attributes can now be filtered out by supplying a custom function to the new config option attributeFilter. For instance, to remove null attribute values from the output, you can supply the config option attributeFilter: (key, val) => val === null (#58 and #10)
  • devDependencies: migrated from babel-eslint to @babel/eslint-parser, migrated from uglify-es to uglify-js

Version 2.2.0

  • Initial support for XML comments (#47)

Version 2.1.1

  • Fix for #48 (various 0-depth issues, bad "is output start" logic)

Version 2.0.0 (breaking)

  • New: automatic entity escaping for &, <, and > characters. In addition, quotes " in attributes are also escaped (see #41). Prior to this, users had to provide their own filter manually. Note that jstoxml makes an effort not to escape entities that appear to have already been encoded, to prevent double-encoding issues.
    • E.g. toXML({ foo: '1 < 2 & 2 > 1' }); // -> "<foo>1 &lt; 2 &amp; 2 &gt; 1</foo>"
    • To restore the default behavior from v1.x.x, simply pass in false to filter and attributesFilter options: toXML({ foo: '1 < 2 & 2 > 1' }, { filter: false, attributesFilter: false }); // -> "<foo>1 < 2 & 2 > 1</foo>"

For more changelog history, see CHANGELOG.md.

Past changes

  • See CHANGELOG.md for a full history of changes.

Other Examples

First you'll want to require jstoxml in your script, and assign the result to the namespace variable you want to use (in this case jstoxml):

// Node
const { toXML } = require('jstoxml');

// Browser (with the help of something like Webpack or Rollup)
import { toXML } from 'jstoxml';

// Browser global fallback (requires no bundler)
var toXML = window.jstoxml.toXML;

Example 1: Simple object

toXML({
    foo: 'bar',
    foo2: 'bar2'
});

Output:

<foo>bar</foo><foo2>bar2</foo2>

Note: because JavaScript doesn't allow duplicate key names, only the last defined key will be outputted. If you need duplicate keys, please use an array instead (see Example 2 below).

Example 2: Simple array (needed for duplicate keys)

toXML([
    {
        foo: 'bar'
    },
    {
        foo: 'bar2'
    }
]);

Output:

<foo>bar</foo><foo>bar2</foo>

Example 3: Simple functions

toXML({ currentTime: () => new Date() });

Output:

<currentTime>Mon Oct 02 2017 09:34:54 GMT-0700 (PDT)</currentTime>

Example 4: XML tag attributes

toXML({
    _name: 'foo',
    _content: 'bar',
    _attrs: {
        a: 'b',
        c: 'd'
    }
});

Output:

<foo a="b" c="d">bar</foo>

Example 5: Tags mixed with text content

To output text content, set a key to null:

toXML({
    text1: null,
    foo: 'bar',
    text2: null
});

Output:

text1<foo>bar</foo>text2

Example 6: Nested tags (with indenting)

const xmlOptions = {
    header: false,
    indent: '  '
};

toXML(
    {
        a: {
            foo: 'bar',
            foo2: 'bar2'
        }
    },
    xmlOptions
);

Output:

<a>
  <foo>bar</foo>
  <foo2>bar2</foo2>
</a>

Example 7: Nested tags with attributes (with indenting)

const xmlOptions = {
    header: false,
    indent: '  '
};

toXML(
    {
        ooo: {
            _name: 'foo',
            _attrs: {
                a: 'b'
            },
            _content: {
                _name: 'bar',
                _attrs: {
                    c: 'd'
                }
            }
        }
    },
    xmlOptions
);

Output:

<ooo>
  <foo a="b">
    <bar c="d"/>
  </foo>
</ooo>

Note that cases like this might be especially hard to read because of the deep nesting, so it's recommend you use something like this pattern instead, which breaks it up into more readable pieces:

const bar = {
    _name: 'bar',
    _attrs: {
        c: 'd'
    }
};

const foo = {
    _name: 'foo',
    _attrs: {
        a: 'b'
    },
    _content: bar
};

const xmlOptions = {
    header: false,
    indent: '  '
};

return toXML(
    {
        ooo: foo
    },
    xmlOptions
);

Example 8: Complex functions

Function outputs will be processed (fed back into toXML), meaning that you can output objects that will in turn be converted to XML.

toXML({
    someNestedXML: () => {
        return {
            foo: 'bar'
        };
    }
});

Output:

<someNestedXML><foo>bar</foo></someNestedXML>

Example 9: RSS Feed

const xmlOptions = {
    header: true,
    indent: '  '
};

toXML(
    {
        _name: 'rss',
        _attrs: {
            version: '2.0'
        },
        _content: {
            channel: [
                {
                    title: 'RSS Example'
                },
                {
                    description: 'Description'
                },
                {
                    link: 'google.com'
                },
                {
                    lastBuildDate: () => new Date()
                },
                {
                    pubDate: () => new Date()
                },
                {
                    language: 'en'
                },
                {
                    item: {
                        title: 'Item title',
                        link: 'Item link',
                        description: 'Item Description',
                        pubDate: () => new Date()
                    }
                },
                {
                    item: {
                        title: 'Item2 title',
                        link: 'Item2 link',
                        description: 'Item2 Description',
                        pubDate: () => new Date()
                    }
                }
            ]
        }
    },
    xmlOptions
);

Output:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>RSS Example</title>
    <description>Description</description>
    <link>google.com</link>
    <lastBuildDate>Sat Jul 30 2011 18:14:25 GMT+0900 (JST)</lastBuildDate>
    <pubDate>Sat Jul 30 2011 18:14:25 GMT+0900 (JST)</pubDate>
    <language>en</language>
    <item>
      <title>Item title</title>
      <link>Item link</link>
      <description>Item Description</description>
      <pubDate>Sat Jul 30 2011 18:33:47 GMT+0900 (JST)</pubDate>
    </item>
    <item>
      <title>Item2 title</title>
      <link>Item2 link</link>
      <description>Item2 Description</description>
      <pubDate>Sat Jul 30 2011 18:33:47 GMT+0900 (JST)</pubDate>
    </item>
  </channel>
</rss>

Example 10: Podcast RSS Feed

(see the Apple docs for more information)

const xmlOptions = {
    header: true,
    indent: '  '
};

toXML(
    {
        _name: 'rss',
        _attrs: {
            'xmlns:itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd',
            version: '2.0'
        },
        _content: {
            channel: [
                {
                    title: 'Title'
                },
                {
                    link: 'google.com'
                },
                {
                    language: 'en-us'
                },
                {
                    copyright: 'Copyright 2011'
                },
                {
                    'itunes:subtitle': 'Subtitle'
                },
                {
                    'itunes:author': 'Author'
                },
                {
                    'itunes:summary': 'Summary'
                },
                {
                    description: 'Description'
                },
                {
                    'itunes:owner': {
                        'itunes:name': 'Name',
                        'itunes:email': 'Email'
                    }
                },
                {
                    _name: 'itunes:image',
                    _attrs: {
                        href: 'image.jpg'
                    }
                },
                {
                    _name: 'itunes:category',
                    _attrs: {
                        text: 'Technology'
                    },
                    _content: {
                        _name: 'itunes:category',
                        _attrs: {
                            text: 'Gadgets'
                        }
                    }
                },
                {
                    _name: 'itunes:category',
                    _attrs: {
                        text: 'TV &amp; Film'
                    }
                },
                {
                    item: [
                        {
                            title: 'Podcast Title'
                        },
                        {
                            'itunes:author': 'Author'
                        },
                        {
                            'itunes:subtitle': 'Subtitle'
                        },
                        {
                            'itunes:summary': 'Summary'
                        },
                        {
                            'itunes:image': 'image.jpg'
                        },
                        {
                            _name: 'enclosure',
                            _attrs: {
                                url: 'http://example.com/podcast.m4a',
                                length: '8727310',
                                type: 'audio/x-m4a'
                            }
                        },
                        {
                            guid: 'http://example.com/archive/aae20050615.m4a'
                        },
                        {
                            pubDate: 'Wed, 15 Jun 2011 19:00:00 GMT'
                        },
                        {
                            'itunes:duration': '7:04'
                        },
                        {
                            'itunes:keywords': 'salt, pepper, shaker, exciting'
                        }
                    ]
                },
                {
                    item: [
                        {
                            title: 'Podcast2 Title'
                        },
                        {
                            'itunes:author': 'Author2'
                        },
                        {
                            'itunes:subtitle': 'Subtitle2'
                        },
                        {
                            'itunes:summary': 'Summary2'
                        },
                        {
                            'itunes:image': 'image2.jpg'
                        },
                        {
                            _name: 'enclosure',
                            _attrs: {
                                url: 'http://example.com/podcast2.m4a',
                                length: '655555',
                                type: 'audio/x-m4a'
                            }
                        },
                        {
                            guid: 'http://example.com/archive/aae2.m4a'
                        },
                        {
                            pubDate: 'Wed, 15 Jul 2011 19:00:00 GMT'
                        },
                        {
                            'itunes:duration': '11:20'
                        },
                        {
                            'itunes:keywords': 'foo, bar'
                        }
                    ]
                }
            ]
        }
    },
    xmlOptions
);

Output:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
  <channel>
    <title>Title</title>
    <link>google.com</link>
    <language>en-us</language>
    <copyright>Copyright 2011</copyright>
    <itunes:subtitle>Subtitle</itunes:subtitle>
    <itunes:author>Author</itunes:author>
    <itunes:summary>Summary</itunes:summary>
    <description>Description</description>
    <itunes:owner>
      <itunes:name>Name</itunes:name>
      <itunes:email>Email</itunes:email>
    </itunes:owner>
    <itunes:image href="image.jpg"/>
    <itunes:category text="Technology">
      <itunes:category text="Gadgets"/>
    </itunes:category>
    <itunes:category text="TV &amp; Film"/>
    <item>
      <title>Podcast Title</title>
      <itunes:author>Author</itunes:author>
      <itunes:subtitle>Subtitle</itunes:subtitle>
      <itunes:summary>Summary</itunes:summary>
      <itunes:image>image.jpg</itunes:image>
      <enclosure url="http://example.com/podcast.m4a" length="8727310" type="audio/x-m4a"/>
      <guid>http://example.com/archive/aae20050615.m4a</guid>
      <pubDate>Wed, 15 Jun 2011 19:00:00 GMT</pubDate>
      <itunes:duration>7:04</itunes:duration>
      <itunes:keywords>salt, pepper, shaker, exciting</itunes:keywords>
    </item>
    <item>
      <title>Podcast2 Title</title>
      <itunes:author>Author2</itunes:author>
      <itunes:subtitle>Subtitle2</itunes:subtitle>
      <itunes:summary>Summary2</itunes:summary>
      <itunes:image>image2.jpg</itunes:image>
      <enclosure url="http://example.com/podcast2.m4a" length="655555" type="audio/x-m4a"/>
      <guid>http://example.com/archive/aae2.m4a</guid>
      <pubDate>Wed, 15 Jul 2011 19:00:00 GMT</pubDate>
      <itunes:duration>11:20</itunes:duration>
      <itunes:keywords>foo, bar</itunes:keywords>
    </item>
  </channel>
</rss>

Example 11: Custom filter for XML entities, or whatever

const xmlOptions = {
    contentReplacements: {
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&apos;',
        '&': '&amp;'
    }
};

toXML(
    {
        foo: '<a>',
        bar: '"b"',
        baz: "'&whee'"
    },
    xmlOptions
);

Output:

<foo>&lt;a&gt;</foo><bar>&quot;b&quot;</bar><baz>&apos;&amp;whee&apos;</baz>

Example 11b: Custom filter for XML attributes

const xmlOptions = {
    attributeReplacements: {
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&apos;',
        '&': '&amp;'
    }
};

toXML(
    {
        _name: 'foo',
        _attrs: { a: '<"\'&"foo>' }
    },
    xmlOptions
);

Output:

<foo a="&lt;&quot;&apos;&amp;&quot;foo&gt;"/>

Example 12: Avoiding self-closing tags

If you don't want self-closing tags, you can pass in a special config option selfCloseTags:

const xmlOptions = {
    selfCloseTags: false
};

toXML(
    {
        foo: '',
        bar: undefined
    },
    xmlOptions
);

Output:

<foo></foo><bar>whee</bar>

Example 13: Custom XML header

const xmlOptions = {
    header: '<?xml version="1.0" encoding="UTF-16" standalone="yes"?>'
};

toXML(
    {
        foo: 'bar'
    },
    xmlOptions
);

Output:

<?xml version="1.0" encoding="UTF-16" standalone="yes"?><foo>bar</foo><foo2>bar2</foo2>

Example 14: Emoji attribute support (needed for AMP)

toXML({
    html: {
        _attrs: {
            '⚡': true
        }
    }
});

Output:

<html ⚡/>

Example 15: Duplicate attribute key support

toXML({
    html: {
        _attrs: [
            {
                lang: 'en'
            },
            {
                lang: 'klingon'
            }
        ]
    }
});

Output:

<html lang="en" lang="klingon"/>

Example 16: XML comments

toXML(
    {
        _comment: 'Some important comment',
        a: {
            b: [1, 2, 3]
        }
    },
    { indent: '    ' }
);

Output:

<!-- Some important comment -->
<a>
    <b>1</b>
    <b>2</b>
    <b>3</b>
</a>

Example 17: Multiple XML comments

toXML(
    [
        { _comment: 'Some important comment' },
        { _comment: 'This is a very long comment!' },
        { _comment: 'More important exposition!' },
        { a: { b: [1, 2, 3] } }
    ],
    { indent: '    ' }
);

Output:

<!-- Some important comment -->
<!-- This is a very long comment! -->
<!-- More important exposition! -->
<a>
    <b>1</b>
    <b>2</b>
    <b>3</b>
</a>

License

MIT

More Repositories

1

energize.js

A tiny JavaScript snippet to make links snappy on touch devices
JavaScript
181
star
2

touche

Touché: bringing touch events to non-touch browsers (how touching!). No dependencies. No code bloat.
JavaScript
144
star
3

tle.js

🛰️ Satellite TLE tools in JavaScript: get lat/lon of satellites, get look angles, plot orbit lines, extract individual TLE elements, etc
JavaScript
127
star
4

eslint-plugin-test-selectors

Enforces that data-test-id attributes are added to interactive DOM elements (JSX) to help with UI testing. JSX only.
JavaScript
27
star
5

jsconf-2014

JSConf 2014 talk: Realtime Satellite Tracking in the Browser
JavaScript
21
star
6

mobile-console

Debug console bookmarklet for mobile devices. Overrides console.log, replacing it with an on-screen console that appears at the bottom of the window. mobile-console also logs all messages to a remote server, which can write the messages to a log or display them on a desktop browser.
7
star
7

transcoder

A simple utility for web developers to convert to base64, hex, binary, md5, etc, as well as useful tools such as a CSS minifier, jsMin, Closure Compiler (coming soon), and a JavaScript-based QR code generator. With desktop drag and drop capability!
PHP
6
star
8

negative-scroll-blur

Make stuff blurry when there's negative top scroll
JavaScript
5
star
9

trackthatsatellite.com

100% clientside satellite tracker
JavaScript
5
star
10

normalize-mobile.css

Normalize.css for mobile minus desktop fixes (also minus IE star/underscore hacks)
5
star
11

gps-time.js

Small utility to convert times between GPS epoch (midnight January 6, 1980) and Unix epoch (midnight January 1, 1970), taking into account leap seconds.
JavaScript
5
star
12

s5mod

Modification and updates to the s5 presentation platform
JavaScript
3
star
13

jest-bug-test-file-stub

JavaScript
3
star
14

link-aggregator

Pulls together topical links from a variety of sources, ranking them by popularity
JavaScript
3
star
15

react-hover-slideshow

Iterates through an image slideshow based on cursor/touch position.
JavaScript
3
star
16

covid-19-map-south-carolina

Interactive map of COVID-19 cases by zip code in South Carolina
JavaScript
2
star
17

simple-cors-server

Simple HTTP server with CORS enabled (similar to Python's SimpleHTTPServer)
JavaScript
2
star
18

deep-object-assign-with-reduce

Deep merging of objects with the same function signature as Object.assign() (useful for overriding default options objects)
JavaScript
2
star
19

frontendstuff

frontendstuff.com
JavaScript
2
star
20

Leveler

Brings older JavaScript implementation up to the level by providing new methods (string trim, Date.now, etc.)
JavaScript
1
star
21

covid-19-data-south-carolina

JavaScript
1
star
22

little-time

Minimalist timestamp manipulator and formatter inspired by moment.js
JavaScript
1
star
23

flickryql

Flickr + YQL
1
star
24

page-curl

Flipboard-style page curl effects
1
star
25

sudoku

Simple sudoku solver in JavaScript (just for fun!)
JavaScript
1
star
26

react-hook-visible-satellites

React hook that returns satellites currently visible in the sky overhead.
JavaScript
1
star
27

parse-scraped-times

Helper for managing the insane variations in writing times in HTML. Needed for getting published/updated times of articles and websites in general.
JavaScript
1
star
28

cbsi-tech-talks

CBSi Tech Talks stuff - notes, etc
1
star
29

gallery-flickr

Useful Flickr widget for YUI3
JavaScript
1
star
30

writers-friend

Distraction-free simple writing experience for the local browser (no network calls)
JavaScript
1
star