Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/davidcalhoun/jstoxml

JavaScript object to XML converter (useful for RSS, podcasts, GPX, AMP, etc)
https://github.com/davidcalhoun/jstoxml

amp amp-html gpx html jsx jsx-syntax podcast rss xml

Last synced: about 3 hours ago
JSON representation

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

Awesome Lists containing this project

README

        

# jstoxml

[![npm downloads](https://img.shields.io/npm/dm/jstoxml.svg)](https://www.npmjs.com/package/jstoxml)

### 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](http://www.rssboard.org/rss-specification) and [Podcasts](http://www.apple.com/itunes/podcasts/specs.html).

This is inspired by [node-jsontoxml](https://github.com/soldair/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

```js
import { toXML } from 'jstoxml';

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

toXML(content, config);
/*
Output:
`
bar
`
*/
```

### 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` | `{ "<": "<", ">": ">", "&": "&", "\"": """ }` | XML attribute value substrings to replace (e.g. ``). Does not double encode HTML entities (e.g. `<` is preserved and NOT converted to `&lt`). |
| attributeFilter | `function` | | Filters out attributes based on user-supplied function. |
| attributeExplicitTrue | `boolean` | `false` | When true explicitly outputs `true` attribute value strings, e.g. `` instead of ``. |
| contentMap | `function` | | Custom map function to transform XML content. Runs after `contentReplacements`. |
| contentReplacements | `object` | `{ "<": "<", ">": ">", "&": "&", "\"": """ }` | XML content strings to replace (e.g. `This & that` becomes `This & that`). |
| 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 `null` to instead appear as `` 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](https://github.com/davidcalhoun/jstoxml/issues/47))

#### Version 2.1.1

- Fix for [#48](https://github.com/davidcalhoun/jstoxml/issues/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](/../../issues/41)). Prior to this, users [had to provide their own filter manually](https://github.com/davidcalhoun/jstoxml/issues/4#issuecomment-19165730). 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' }); // -> "1 < 2 & 2 > 1"`
- 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 }); // -> "1 < 2 & 2 > 1"`

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):

```javascript
// 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

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

Output:

```
barbar2
```

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)

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

Output:

```
barbar2
```

#### Example 3: Simple functions

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

Output:

```
Mon Oct 02 2017 09:34:54 GMT-0700 (PDT)
```

#### Example 4: XML tag attributes

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

Output:

```
bar
```

#### Example 5: Tags mixed with text content

To output text content, set a key to null:

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

Output:

```
text1bartext2
```

#### Example 6: Nested tags (with indenting)

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

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

Output:

```

bar
bar2

```

#### Example 7: Nested tags with attributes (with indenting)

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

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

Output:

```



```

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:

```javascript
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.

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

Output:

```
bar
```

#### Example 9: RSS Feed

```javascript
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:

```


RSS Example
Description
google.com
Sat Jul 30 2011 18:14:25 GMT+0900 (JST)
Sat Jul 30 2011 18:14:25 GMT+0900 (JST)
en

Item title
Item link
Item Description
Sat Jul 30 2011 18:33:47 GMT+0900 (JST)


Item2 title
Item2 link
Item2 Description
Sat Jul 30 2011 18:33:47 GMT+0900 (JST)

```

#### Example 10: Podcast RSS Feed

(see the [Apple docs](http://www.apple.com/itunes/podcasts/specs.html) for more information)

```javascript
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 & 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:

```


Title
google.com
en-us
Copyright 2011
Subtitle
Author
Summary
Description

Name
Email







Podcast Title
Author
Subtitle
Summary
image.jpg

http://example.com/archive/aae20050615.m4a
Wed, 15 Jun 2011 19:00:00 GMT
7:04
salt, pepper, shaker, exciting


Podcast2 Title
Author2
Subtitle2
Summary2
image2.jpg

http://example.com/archive/aae2.m4a
Wed, 15 Jul 2011 19:00:00 GMT
11:20
foo, bar

```

#### Example 11: Custom filter for XML entities, or whatever

```javascript
const xmlOptions = {
contentReplacements: {
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'&': '&'
}
};

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

Output:

```
<a>"b"'&whee'
```

#### Example 11b: Custom filter for XML attributes

```javascript
const xmlOptions = {
attributeReplacements: {
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'&': '&'
}
};

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

Output:

```

```

#### Example 12: Avoiding self-closing tags

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

```javascript
const xmlOptions = {
selfCloseTags: false
};

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

Output:

```
whee
```

#### Example 13: Custom XML header

```javascript
const xmlOptions = {
header: ''
};

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

Output:

```
barbar2
```

#### Example 14: Emoji attribute support (needed for AMP)

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

Output:

```

```

#### Example 15: Duplicate attribute key support

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

Output:

```