Giter Club home page Giter Club logo

xmlbuilder-js's Introduction

xmlbuilder-js

An XML builder for node.js similar to java-xmlbuilder.

License NPM Version NPM Downloads

Travis Build Status AppVeyor Build status Dev Dependency Status Code Coverage

Announcing xmlbuilder2:

The new release of xmlbuilder is available at xmlbuilder2! xmlbuilder2 has been redesigned from the ground up to be fully conforming to the modern DOM specification. It supports XML namespaces, provides built-in converters for multiple formats, collection functions, and more. Please see upgrading from xmlbuilder in the wiki.

New development will be focused towards xmlbuilder2; xmlbuilder will only receive critical bug fixes.

Installation:

npm install xmlbuilder

Usage:

var builder = require('xmlbuilder');

var xml = builder.create('root')
  .ele('xmlbuilder')
    .ele('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
  .end({ pretty: true});

console.log(xml);

will result in:

<?xml version="1.0"?>
<root>
  <xmlbuilder>
    <repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
  </xmlbuilder>
</root>

It is also possible to convert objects into nodes:

var builder = require('xmlbuilder');

var obj = {
  root: {
    xmlbuilder: {
      repo: {
        '@type': 'git', // attributes start with @
        '#text': 'git://github.com/oozcitak/xmlbuilder-js.git' // text node
      }
    }
  }
};

var xml = builder.create(obj).end({ pretty: true});
console.log(xml);

If you need to do some processing:

var builder = require('xmlbuilder');

var root = builder.create('squares');
root.com('f(x) = x^2');
for(var i = 1; i <= 5; i++)
{
  var item = root.ele('data');
  item.att('x', i);
  item.att('y', i * i);
}

var xml = root.end({ pretty: true});
console.log(xml);

This will result in:

<?xml version="1.0"?>
<squares>
  <!-- f(x) = x^2 -->
  <data x="1" y="1"/>
  <data x="2" y="4"/>
  <data x="3" y="9"/>
  <data x="4" y="16"/>
  <data x="5" y="25"/>
</squares>

Documentation:

See the wiki for details and examples for more complex examples.

Donations:

Please consider becoming a backer or sponsor to help support development.

Donate Button

xmlbuilder-js's People

Contributors

addaleax avatar atlas48 avatar bnjmnt4n avatar btmills avatar btsimonh avatar darashi avatar dependabot[bot] avatar gabteles avatar halfdan avatar jscheid avatar luanmuniz avatar nickclaw avatar oozcitak avatar piroor avatar rvagg avatar sandersn avatar tomhughes avatar tootallnate avatar tregagnon avatar unclespike avatar wdavidw avatar zeikjt 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

xmlbuilder-js's Issues

Elements with null values not treated consistently

This is a really great tool. However, I ran into an issue while trying to create documents that had iterations over their structure. I couldn't figure out how to build them with the concatenated element approach, so I used the object approach instead. But I found that elements are not treated consistently between them. Here is demonstration code:

var builder = require('xmlbuilder');

var doc1 = builder.create('doc');
doc1.ele("parent").
    ele("listItem").
    ele("child1", "present").up().
    ele("child2", null).up().up().
    ele("listItem").
    ele("child1", "present").up().
    ele("child2", null);
console.log(doc1.toString({pretty: true}));

var doc2 = builder.create('doc');
var contents = {
    parent: {
        '#list': [
            {
                listItem: {
                    'child1': "present",
                    'child2': null
                }
            },
            {
                listItem: {
                    'child1': "present",
                    'child2': null
                }
            }
        ]
    }
};
doc2.ele(contents);
console.log(doc2.toString({pretty: true}));

I need the resulting document to look like the doc1 results when there are null values in the data. Can you help with this? Is there a way to use the concatenated ele() calls to produce a variable number of listItems in the structure?

Thanks,

Doesn't install without make on the system

I'm trying to install the tools for the Ace editor and it's breaking because the prepublish script requires make to be installed. Any idea what I should do other than install make?

Is it possible to insert a complete XML tree into one that is already created at a specific point?

Hello again!

I want to know if its possible to insert an XML tree (complete with sub-objects) into an already created tree at a specific node in the tree. Something like this:

   var doc = builder.create('request', {'version': '1.0', 'encoding': 'UTF-8'});
    var staticXML = {
        '#list': [
                    {
                        control : {
                            'senderid': 'stuff',
                            'password': 'password',
                            'controlid': 'stuff',
                            'dtdversion': '2.1'
                                },

                        operation: {
                            authentication: {
                                login: {
                                    'userid': 'userid',
                                    'companyid': 'companyname',
                                    'password': 'password'
                                        }
                                    },

                            content: {
                                'function': {
                                    '@controlid': 'stuff',
                                    create_billbatch: {
                                    'batchtitle': 'Upload: ' + getDateTime
                                    }
                             }
                          }
                        }
                    }
                ]
            };

    doc.ele(staticXML);
    console.log(doc.toString({ pretty: true }));

        var pageTwo = builder.create('create_bill', {'version': '1.0', 'encoding': 'UTF-8'});
        var varrowEmployee = {
            '#list': [
                        {
                            'vendorid': 'ID Here',
                            datecreated: {
                                'year': 'Year Here',
                                'month': 'Month Here',
                                'day': 'Day Here'
                            },
                            datedue: {
                                'year': 'Year Here',
                                'month': 'Month Here', 
                                'day': 'Day Here'
                            },
                            'billno': 'Bill Number Here',
                            'description': 'Description Here', 
                            billitems: {}
                        }
            ]
        };

The above tree would be inserted as a child of the node batchtitle in the first listed tree. Another tree would also be inserted as a child of billitems

http://pastebin.com/MZRzxMin

As you can see, there can be multiple children inserted, and it cannot be statically created as the values are being pulled from a parsed excel sheet. I know there are ways to traverse through the lists, I am just not sure how children trees can be inserted.

Thank you

?xml version header

I just started using this package. The first thing I'm trying to do is build the prolog. I got this so far:

    var xfdf = XmlBuilder.create({
      xfdf: {
        '@xmlns': 'http://ns.adobe.com/xfdf/',
        '@xml:space': 'preserve'
      }
    });

The result is a file that looks like this:

<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve"/>

xfdf is the root.

How do I get the <?xml version="1.0" encoding="UTF-8" ?> to write to the file?

Typo in source code

On line of 36 of XmlFragment.coffee or line 23 of XmlFragment.js, "atrribues" should read "attributes". I believe this occurs when you use element.ele('title', title); syntax instead of element.ele('title').text(title); Perhaps this syntax was not meant to be supported?

Root element will not accept attributes

I'm trying to add attributes to the root element but they do not appear when I call toString(). The only item that is returned is the element itself...

For Example:

  var xmlbuilder = require('xmlbuilder');

  // Create the builder instance
  var stream_doc = xmlbuilder.create();

  // Start the stream element
  stream_doc.begin('stream:stream', {version: '1.0'});

  // Add the appropriate attributes
  stream_doc.att('from', '[email protected]');
  stream_doc.att('to', 'example.com');
  stream_doc.att('xml:lang', 'en');
  stream_doc.att('version', '1.0');
  stream_doc.att('xmlns', 'jabber:client');
  stream_doc.att('xmlns:stream', 'http://etherx.jabber.org/streams');

Will return:

<stream:stream/>

Instead of:

<?xml version='1.0'?>
<stream:stream
  from='[email protected]'
  to='example.com'
  version='1.0'
  xml:lang='en'
  xmlns='jabber:client'
  xmlns:stream='http://etherx.jabber.org/streams' />

format problem in end with pretty true

problem occurs in the file : XMLStringifier.coffee

  elEscape: (str) ->
    str.replace(/&/g, '&amp;')
       .replace(/</g, '&lt;')
       .replace(/>/g, '&gt;')
       .replace(/\r/g, '&#xD;')

Sometimes, we need to put CDATA in the same line with tags, so we might write code like this:

some_element.ele('url', null,'\<![CDATA[' + 'http://www.github.com' + ']]\>');

while the origin multi-line is like this:

var url = some_element.ele('url'));
url.dat('http://www.github.com')

if we 'replace(/</g, '<')' and replace(/>/g, '>'), it will cause problems.

Do you think it is necessary to take the one line requirement into account?
Just like provide some parameters in pretty function?

.txt() creates empty tag when passed value of 0

When passing a value of 0 to .txt(), it creates an empty tag. This results in invalid XML that cannot be parsed. Here's how to reproduce this problem:

var builder = require('xmlbuilder');
var xml = builder.begin('bla');
xml.ele('stuff').txt(0);
console.log(xml.toString());

This prints out the following:

<bla><stuff></></stuff></bla>

instead of

<bla><stuff>0</stuff></bla>

A work-around is to coerce the value into a string by using ''+value, but that is obviously error-prone.

Missing XML declaration with new root change

First, thank you for the work on xmlbuilder. It's been hugely helpful.

I need toString() to include the XML declaration (e.g. <?xml version="1.0"?>). This was working until the recent change with the root method.

My previous code:

var xml = xmlBuilder.create().begin('methodResponse', { version: '1.0' })
// ...Builds up XML...
// Prints <?xml version="1.0"?><methodResponse>...</methodResponse>
xml.up().toString()

I updated to v0.2.1 and received an error This node has no parent.

I tried updating the code to use root() instead of up() at the end like so:

var xml = xmlBuilder.create().begin('methodResponse', { version: '1.0' })
// ...Builds up XML...
// Prints <methodResponse>...</methodResponse>
xml.root().toString()

But root() prints the XML without the XML declaration. xml.root().up().toString() throws the same This node has no parent error and xml.root().prev() rightly complains no siblings.

Support Node 0.11

Node 0.11 is currently not supported and not even tested on. It should be added to the testing infrastructure with failures allowed and after all the issues are resolved, it should be tested & supported fully.

Node 0.12 is supposed to come soon so at least seeing what the issues may be should be done.

Parsing from string

It would be awesome to have a string parser which returns a xmlbuilder object.

Can I create an element that is an object?

Is it possible to have an object parsed as XML, like in the sample below?

myObj = {};
myObj.name = "Sample Name";
myObj.text = "Sample Text";

var xml = builder.create('root').ele('tag', myObj);

and have it generate an xml like this?

<root>
  <tag>
    <name>Sample Name</name>
    <text>Sample Text</text>
  </tag>
</root>

Thank you.

How to apply attribute decorator to sub-object in list?

Hey there,

I've been trying to apply the attribute decorator, '@', to a nested object I have in my xml structure. I've been wracking my brain for a while and cannot come with the most likely obvious syntax I'm missing. Not sure if this belongs here, but any help is appreciated.

        var doc = builder.create('request', {'version': '1.0', 'encoding': 'UTF-8'});
        var staticXML = {
            '#list': [
                        {
                            control : {
                                'senderid': 'stuff',
                                'password': 'password',
                                'controlid': 'stuff',
                                'dtdversion': '2.1'
                                    },

                            operation: {
                                authentication: {
                                    login: {
                                        'userid': 'userid',
                                        'companyid': 'companyname',
                                        'password': 'password'
                                            }
                                        },

                                content: {
                                    'function': {
                                        create_billbatch: {
                                        'batchtitle': 'Upload: ' + getDateTime
                                        }
                                 }
                              }
                            }
                        }
                    ]
                };

        doc.ele(staticXML);
        console.log(doc.toString({ pretty: true }));

I have been attempting to apply an attribute to the "function" nested object but am failing. How would this happen?

Npm install only contains package.json

I've been trying to install the windows azure sdk today, but it tells me it cannot run because xmlbuilder is not installed. Even if I install it by myself the folder in node_modules only contains package.json. Maybe is it due to the down of the npm registry today.

nested lodash path nightmare in windows!

the loadash structure is nested, make the path name tooooooo long!
it take me five hour to solve this ( it works in win7 ,but do not work in xp ,really hard to find out)
please try use one lodash or something.

How to use raw text node with chained syntax?

I have an example built from the usage shown on the Readme:

var xml = builder.create('root', {version: '1.0', encoding: 'UTF-8'}) // xml is built XML file
  .ele('header', data)
  .end({pretty: true});
console.log(xml);

data is HTML content from a file. Ex: fs.readFile(inputFile, "UTF-8", function (err, data) { ...});.

xmlbuilder is encoding the tags on the incoming html file (into &lt;h1&gt;... for example), so I tried using .raw from https://github.com/oozcitak/xmlbuilder-js/wiki. Ex:

.ele.raw('header', data)

but Node just returns an error: "TypeError: Object function (name, attributes, text) {
return this.element(name, attributes, text);
} has no method 'raw'"

How can I use methods such as raw with the chained syntax?

Thanks!

command npm pack drop error

Good day: I was trying to pack your module, cause i need to install it on my machine that is not connected to the internet. So when I proceed to do "npm pack" command in the directory of your module i got error. This is the entire logfile, hope this be useful:

npm-debug.txt

0 info it worked if it ends with ok
1 verbose cli [ 'D:\nodejs\node.exe',
1 verbose cli 'D:\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'pack' ]
2 info using [email protected]
3 info using [email protected]
4 verbose node symlink D:\nodejs\node.exe
5 verbose cache add [ '.', null ]
6 verbose cache add name=undefined spec="." args=[".",null]
7 verbose parsed url { protocol: null,
7 verbose parsed url slashes: null,
7 verbose parsed url auth: null,
7 verbose parsed url host: null,
7 verbose parsed url port: null,
7 verbose parsed url hostname: null,
7 verbose parsed url hash: null,
7 verbose parsed url search: null,
7 verbose parsed url query: null,
7 verbose parsed url pathname: '.',
7 verbose parsed url path: '.',
7 verbose parsed url href: '.' }
8 silly lockFile 3a52ce78- .
9 verbose lock . C:\Users\Linda\AppData\Roaming\npm-cache\3a52ce78-.lock
10 verbose tar pack [ 'C:\Users\Linda\AppData\Roaming\npm-cache\xmlbuilder\2.4.4\package.tgz',
10 verbose tar pack '.' ]
11 verbose tarball C:\Users\Linda\AppData\Roaming\npm-cache\xmlbuilder\2.4.4\package.tgz
12 verbose folder .
13 info prepublish [email protected]
14 verbose unsafe-perm in lifecycle true
15 info [email protected] Failed to exec prepublish script
16 error addLocalDirectory Could not pack "." to "C:\Users\Linda\AppData\Roaming\npm-cache\xmlbuilder\2.4.4\package.tgz"
17 silly lockFile 3a52ce78- .
18 silly lockFile 3a52ce78- .
19 error addLocal Could not install .
20 error [email protected] prepublish: coffee -co lib/ src/*.coffee
20 error Exit status 1
21 error Failed at the [email protected] prepublish script.
21 error This is most likely a problem with the xmlbuilder package,
21 error not with npm itself.
21 error Tell the author that this fails on your system:
21 error coffee -co lib/ src/*.coffee
21 error You can get their info via:
21 error npm owner ls xmlbuilder
21 error There is likely additional logging output above.
22 error System Windows_NT 6.1.7601
23 error command "D:\nodejs\node.exe" "D:\nodejs\node_modules\npm\bin\npm-cli.js" "pack"
24 error cwd D:\nodejs\nodeDocs\package\xmlbuilder-js
25 error node -v v0.10.32
26 error npm -v 1.4.28
27 error code ELIFECYCLE
28 verbose exit [ 1, true ]

Character Data testing seems to be wrong

Before adding text, you try to validate the text to ensure it is valid character data.

You appear though to be testing for Entity values in the form %xxx; as well as &xxx; but the % is a legal xml value as character data, as far as I can see. The test probably needs to be a little less strict.

Cliff.

Formatting Object to xml

I'm trying to get an output that looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
    <f href="test2.pdf" />
    <fields>
        <field name="form1[0]">
            <field name="#subform[0]">
                <field name="firstName">
                    <value>john</value>
                </field>
                <field name="middleName">
                    <value>ralph</value>
                </field>
                <field name="lastName">
                    <value>Doe</value>
                </field>
            </field>
       </field>
  </fields>
  <ids original="hashcode" modified="hashcode"/>
</xfdf>

But when I build an object that looks like this it never gets me what I want in the subform:

  obj = {
    'xfdf': {
      '@xmlns': 'http://ns.adobe.com/xfdf/',
      '@xml:space': 'preserve',
      'f': {
        '@href': 'test2.pdf'
      },
      'fields': {
        'field': {
          '@name': 'form1[0]',
          'field': {
            '@name': '#subform[0]',
            'field': {
              '@name': 'firstName',
              'value': 'John'
            },
            'field': {
              '@name': 'middleName',
              'value': 'Ralph'
            },
            'field': {
              '@name': 'lastName',
              'value': 'Doe'
            }
          }
        }
      },
      'ids': {
        '@original': 'hashcode',
        '@modified': 'hashcode'
      }
    }
  };

What am I doing wrong here?

Is there an xml un-builder?

Given an XML string, is there a tool that can generate a JS object (or JSON string) for which XML builder will generate an equivalent XML string?

In particular, tools that I can see online (e.g. http://www.utilities-online.info/xmltojson/#.VK4W82TF-pw) don't handle the #list feature at all, and don't use the @ symbol for tag attributes,
{"-attribute":value} rather than { "@attribute":value}

Support variable in element attribute

The following code:

var builder = require('xmlbuilder');
var a = 'attr1';
var xml = builder.create('root');
.ele('ele', {a: 'value1'}).end({pretty:true});
console.log(xml);

would return:

<?xml version="1.0"?>  
<root>                 
<ele a="value1"/>    
</root>               

instead of the expected:

<?xml version="1.0"?>  
<root>                 
<ele "attr1"="value1"/>    
</root>               

The xmlbuilder seems to treat everything passed to the attribute as string. To implement this, I had to use the attr() function like this:

var builder = require('xmlbuilder');
var a = 'attr1';
var xml = builder.create('root').ele('ele');
var xml1 = xml.att(a, 'value1').end({pretty: true});
console.log(xml1);

I am not sure whether this is a bug or I have some problem in my usage.

Support for String, Number, Boolean objects?

Would you consider a pull request with support for String, Number or Boolean objects?

Currently those are treated as attributes rather than text:

var builder = require('xmlbuilder');
var xml = builder.create('person')
  .ele('email', new String('[email protected]'))
  .end({ pretty: true});
console.log(xml);

Results in:

<?xml version="1.0"?>
<person>
  <email 0="f" 1="o" 2="o" 3="@" 4="b" 5="a" 6="r" 7="." 8="c" 9="o" 10="m"/>
</person>

Empty Elements vs. Self-Closing Tags With Blank Strings

Hey, it looks like if you pass a blank string into an .ele() call, it doesn't create a self-closing tag correctly.

xmlbuilder.create('someElem')
  .ele('selfClose', {}, '')
.root().toString({pretty: true})

Will return as:

<someElem>
  <selfClose></selfClose>
</someElem>

Personally, I expected this to match the null or undefined behavior and have a self-closing tag here:

xmlbuilder.create('someElem')
  .ele('selfClose', {}, undefined)
    .up()
  .ele('anotherSelfClose', {}, null)
.root().toString({pretty: true})

Which will return:

<someElem>
  <selfClose/>
  <anotherSelfClose/>
</someElem>

It's not a huge deal, but it was an issue I'd ran into when accessing a particularly stringent SOAP API. Is this the correct behavoir?

If you don't have time to handle this, could you point me in the right direction in the code? Originally I was going to submit a PR but I wasn't sure about the entry point for this is, and it is very early in the morning.

Attributes in Root Element

Hi,

I try to add an attribute to the root element but so far unsuccessfully.

Here's what I've tried:
var xml = builder.create('root').attr('some_attr', 'some_value');

Hope you can help.

More info on undefined value/name

It would be great if XMLAttribute throw more info about undefined value/name, it can make easier to find where is the null value, I wrote a little modification to help me find where I'm fucking up the code, I hope you can add something like this:

if (name == null) {
    throw new Error("Missing attribute name on " + parent.name + " child");
    // Missing attribute name on Source child
}
if (value == null) {
    throw new Error("Missing attribute value for " + name);
    // Missing attribute value for PseudoCityCode
}

Greetings!!

Loading entire lodash module is slow (100ms+). Require individual methods instead.

I was measuring the load time of my application and I was seeing that 120ms was being added at startup (on average) as a result of this library loading the entire lodash-node module. This was measured using the time-require module.

It's much faster to do a require on the individual methods that are needed from lodash.

For example, instead of the following:

var _ = require('lodash-node');
...
options = _.extend({}, xmldec, doctype, options);

Please do the following instead:

var extend = require('lodash-node/modern/objects/assign');
...
options = extend({}, xmldec, doctype, options);

Hopefully this change can be made so that Node.js applications with this module as a dependency (or nested dependency in my case) will load faster.

Thanks!

Unexpected results

Hi there,

I am trying to use your module in order to generate an XML file from a JSON object with a for loop, but it doesn't seem to work. Just to be sure I tried the example you put on your project's page:

var builder = require('xmlbuilder');
var root = builder.create('squares');
root.com('f(x) = x^2');
for(var i = 1; i <= 5; i++)
{
  var item = root.ele('data');
  item.att('x', i);
  item.att('y', i * i);
}
// Added the next two lines to check the result on the console //
root.end({pretty: true});
console.log(root);

When I do this, I have the following result:

{ parent: 
   { parent: 
      { options: {},
        stringify: [Object],
        rootObject: [Circular],
        xmldec: [Object] },
     options: {},
     stringify: { assertLegalChar: [Function], allowSurrogateChars: undefined },
     name: 'doc',
     children: [ [Circular] ],
     instructions: [],
     attributes: {} },
  options: {},
  stringify: { assertLegalChar: [Function], allowSurrogateChars: undefined },
  name: 'squares',
  children: 
   [ { parent: [Circular],
       options: {},
       stringify: [Object],
       text: 'f(x) = x^2' },
     { parent: [Circular],
       options: {},
       stringify: [Object],
       name: 'data',
       children: [],
       instructions: [],
       attributes: [Object] },
     { parent: [Circular],
       options: {},
       stringify: [Object],
       name: 'data',
       children: [],
       instructions: [],
       attributes: [Object] },
     { parent: [Circular],
       options: {},
       stringify: [Object],
       name: 'data',
       children: [],
       instructions: [],
       attributes: [Object] },
     { parent: [Circular],
       options: {},
       stringify: [Object],
       name: 'data',
       children: [],
       instructions: [],
       attributes: [Object] },
     { parent: [Circular],
       options: {},
       stringify: [Object],
       name: 'data',
       children: [],
       instructions: [],
       attributes: [Object] } ],
  instructions: [],
  attributes: {},
  isRoot: true,
  documentObject: 
   { options: {},
     stringify: { assertLegalChar: [Function], allowSurrogateChars: undefined },
     rootObject: [Circular],
     xmldec: 
      { parent: [Circular],
        options: {},
        stringify: [Object],
        version: '1.0' } } }

I am running node v0.10.29 โ€” any ideas about what is happening here?

Thanks a lot for your help!

indent is ignored

when i set indent: '' (empty indent). It ignores it and makes indent from spaces.

I would like to make each tag from new line but without indention.

invalid XML element names

Invalid XML is easily generated from unsanitized arbitrary objects:

xmlbuilder.create('root').ele({'my name': 'John'})

This will produce bad XML <my name>John</my name>. Maybe some escaping or sanitizing scheme should be implemented? ("my name" -> "my_name" or similar).

Can not find module lodash.bind

Hi,
i have installed xml2js which in turn uses xmlbuilder-js:
I get the following error just when I require xml2js:

module.js:340
    throw err;
          ^
Error: Cannot find module 'lodash.bind'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (c:\Users\London\Apps\showtrackr\node_modules\xml2js\node_modules\xmlbuilder\node_modules\lodash.assign\node_modules\lodash._basecreatecallback\index.js:9:12)
    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 Module.require (module.js:364:17)

Any clues where the problem might arise from? Will ask on xml2js github too.

Build v0.1.4 is incomplete

This version doesn't appear to package up the lib directory. It is only including the package.json file.

Loop certain node

Hi, I'm trying to loop a certain node with xmlbuilder.
The code below doesn't work - I can't figure it out how I should be doing it.
Any help is greatly appreciated.

var xml = builder.create('XML', {'Type': 'ListBuilder'})
    .e('Order', {'No': '123', 'DispDate':'05.09.2013', 'Basket':'123'})
    .e('Head')
      .up()
    .e('BuilderList')
          for (var i=0; i<3; i++) {
            .e('Set', {'LineNo': '1'})
              .e('Pname', 'type')
                .up()
              .e('Count', '1')
                .up()
              .e('PVarString', 'something')
                .up()
              .e('ARTICLE_TEXT_INFO1', 'info1')
                .up()
              .e('ARTICLE_TEXT_INFO2', 'info2')
          }
    .end({pretty: true});

  console.log(xml);

So I would like the <Set> node to be repeat X times.
Thanks.

npm 0.1.6 missing sources

Hi,

i tried to install xmlbuilder via npm but it seems like that you missed to push the actual sources to the npm repository for version 0.1.6. Could you double check this and maybe update the version or push a new version?

Thx for your help.

Regards
Philipp

If a function is defined as a prototype for the Object class, then the XML Fragment adds that function as an attribute, resulting in an invalid xml

Playing with the azure nodejs SDK, which uses xmlbuilder to create their messages, I found an interesting behavior.
I defined a mixin as prototype for the Object class as follows (in .coffee format):
Object.prototype.mixin = () ->
for klass in arguments
# assign class properties
for key, value of klass
@[key] ?= value

# assign instance properties
for key, value of klass.prototype
  @::[key] ?= value

@

After doing that, azure serializes a message as follows:
var doc = xmlbuilder.create();
doc = doc.begin(Constants.QUEUE_MESSAGE_ELEMENT, { version: '1.0', encoding: 'utf-8' });

if (messageJs) {
doc.ele(Constants.MESSAGE_TEXT_ELEMENT)
.txt(new Buffer(messageJs).toString('base64'))
.up();
} else {
doc.ele(Constants.MESSAGE_TEXT_ELEMENT).up();
}

return doc.doc().toString();

By doing so, the mixin ends up as an attribute of the XML, making it invalid.

My solution was to check if a property of an object is a function in the XMLFragment.js file.
I added this:
XMLFragment.prototype.isFunction = function(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}

and then modify the toString prototype to check if an attValue is a function
for (attName in _ref) {
attValue = _ref[attName];
if (this.name === '!DOCTYPE') {
r += ' ' + attValue;
} else if (!this.isFunction(attValue)) {
r += ' ' + attName + '="' + attValue + '"';
}
}

and then everything worked OK!
Maybe that is enough, but it would be good if you check this and change it if this is the desired behavior!

XML Prolog Documentation Issue

Hi there,

With the below example on the documentation site:

var root = require('xmlbuilder').create('xbel',
{ version: '1.0', encoding: 'UTF-8'},
{ pubid: '+//IDN python.org//DTD XML Bookmark Exchange Language 1.0//EN//XML',
sysid: 'http://www.python.org/topics/xml/dtds/xbel-1.0.dtd'
}
);

pubid needs to be pubID and sysid needs to be sysID given the lastest version of the code which I retrieved today via npm.

Regards

Jon

Missing end bracket in usage example

In the usage example, there's a missing end bracket in the following line:

console.log(builder.toString({ pretty: true });

It should read:

console.log(builder.toString({ pretty: true }));

boolean and non-existent attributes

Right now if I pass undefined object as a value, it would output "undefined" string. And to exclude such attributes I would need to filter out the entire attributes object before passing it to xmlbuilder.

Consider this example:

/*
 *  Configuration
 */
var param1 = 123;
// I want to turn off param2, so it doesn't appear in xml. How do I do it here?
var param2;

/*
 *  XML building
 */
var xml = builder.create('root')
  .ele('test', {
    param1: param1,
    param2: param2
  })

Since null and undefined aren't useful anyway, I suggest to exclude them from attributes in the library itself like this:

// expected: <root><test param1="123" /></root>
var xml = builder.create('root').ele('test', { param1: 123, param2: null })

// expected: <root><test param1="123" /></root>
var xml = builder.create('root').ele('test', { param1: 123, param2: undefined })

The same thing is about boolean attributes. If someone pass false, it's unlikely that he wants to get "false" string instead of it. So, I'd like to see this:

// expected: <root><test param1="123" param2="param2" /></root>
var xml = builder.create('root').ele('test', { param1: 123, param2: true })

// expected: <root><test param1="123" /></root>
var xml = builder.create('root').ele('test', { param1: 123, param2: false })

Adding root-level processing instructions ( and processing instructions in general )

Hey there!

First of all, great job with the lib - extremely useful and its interfaces are very clean, I love it.

I was wondering if there was any way to add processing instructions (http://www.w3.org/TR/REC-xml/#sec-pi) in the xml along with the root node and ?xml node.

Basically in order to get something like this ( line 2 of the snippet ) :

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook
   xmlns="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:o="urn:schemas-microsoft-com:office:office"
   xmlns:x="urn:schemas-microsoft-com:office:excel"
   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:html="http://www.w3.org/TR/REC-html40">
  <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
[...]

Thanks and keep it up!

escaping (attributes)

Any plans to support escaping? As far as I can see your application does not support escaping on attributes. Would be really nice if you could add this otherwise we will perhaps contribute this feature in the next 4 weeks.

Thx for developing!

best regards

philipp

toString in XMLBuilder.end

Hey,

In XMLBuilder.coffee in end method looks like:

  # Ends the document and converts string
  end: (options) ->
    toString(options)

I guess there's "@" missing before toString?

possibility to add xmlElement in root.ele

Helo, in my case i've create xml from different objects with toXml method. If parent have child, i create child node like this :

root.ele(child.toXml());

functiontoXml return xmlbuilder root object. It's possible to add an object into another if they are created with different builders ?

If i test this, the child node is in empty node like this :

<root>
    <<child />/>
    <<child />/>
</root>

"Invalid element text" error

I'm generating an RSS feed of events. When the following code hits an escaped apostrophe in the input it dies.

        var entry = items[i];
        channel.ele("item")
          .ele("title")
            .txt(entry.title)
          .ele("link")
            .txt(entry.link)
          .ele("description")
            .txt(entry.description)
          .ele("pubDate")
            .txt(entry.pubDate)
          .ele("media:content", { url: entry.image.src, type: entry.image.type });
Error: Invalid element text: NCAA 2011 Men&apos;s Lacrosse Championships
    at XMLFragment.text (/Users/robert/[...]/node_modules/xmlbuilder/lib/XMLFragment.js:39:15)
    at XMLFragment.txt (/Users/robert/[...]/node_modules/xmlbuilder/lib/XMLFragment.js:156:19)
    at /Users/robert/[...]/events.js:123:14
    at Array.build_output (/Users/robert/[...]/events.js:140:5)
    at EventEmitter._tickCallback (node.js:126:26)

I don't see why this would fail.

I am using node.js v0.4.7 on Mac OS X.

XFDF Prolog

I'm trying to create a XFDF, and am looking for the proper prologs.

I read your prolog page here: https://github.com/oozcitak/xmlbuilder-js/wiki/XML-Prolog

The prolog for my XFDF should look like this:

<?xml version="1.0" encoding="UTF-8" ?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
    <f href="test.pdf" />
    <fields>
   </fields>
   <ids original="some number here" modified="another number here" />
</xfdf>

Error : Version number is required

I'm trying to build this request.

<?xml version="1.0" encoding="utf-8"?>
<Customer xmlns:ns2="http://www.intuit.com/sb/cdm/qbo" xmlns="http://www.intuit.com/sb/cdm/v2">
<TypeOf>Person</TypeOf>
<Name>John Doe</Name>
<Address>
<Line1>Park Avenue</Line1>
<City>Woodland Hills</City>
<CountrySubDivisionCode>CA</CountrySubDivisionCode>
<PostalCode>91367</PostalCode>
</Address>
<Phone>
<DeviceType>Mobile</DeviceType>
<FreeFormNumber>(770) 349-1200</FreeFormNumber>
</Phone>
<Phone>
<DeviceType>Fax</DeviceType>
<FreeFormNumber>(770) 349-1300</FreeFormNumber>
</Phone>
<WebSite>
<URI>http://www.digitalinsight.mint.com/</URI>
</WebSite>
<Email>
<Address>[email protected]</Address>
</Email>
<GivenName>John</GivenName>
<MiddleName>J</MiddleName>
<FamilyName>Doe</FamilyName>
<DBAName>Mint</DBAName>
<SalesTermId>5</SalesTermId>
</Customer>

This is my code.

var builder = require("xmlbuilder");
var doc = builder.create();

var dec = '<?xml version="1.0" encoding="utf-8"?>';

doc.begin("Customer", {"xmlns:ns2":"http://www.intuit.com/sb/cdm/qbo","xmlns":"http://www.intuit.com/sb/cdm/v2"})
    .ele("TypeOf","Person")
    .ele("Name","John Doe")
    .ele("Address")
        .ele("Line1","Park Avenue")
        .ele("City","Woodland Hills")
        .ele("CountrySubDivisionCode","CA")
        .ele("PostalCode","91367")
    .ele("Phone")
        .ele("DeviceType","Mobile")
        .ele("FreeFormNumber","(770) 349-1200")
    .ele("Phone")
        .ele("Fax","Mobile")
        .ele("FreeFormNumber","(770) 349-1300")
    .ele("WebSite")
        .ele("URI","http://www.digitalinsight.mint.com")
    .ele("Email")
        .ele("Address","[email protected]")
    .ele("GivenName","John")
    .ele("MiddleName","J")
    .ele("FamilyName","Doe");

console.log(doc.toString({ pretty: true }));

This is my error.

/Users/thomas/Desktop/forerunner/node_modules/xmlbuilder/lib/XMLBuilder.js:26
        throw new Error("Version number is required");
              ^
Error: Version number is required
    at new XMLBuilder (/Users/thomas/Desktop/forerunner/node_modules/xmlbuilder/lib/XMLBuilder.js:26:15)
    at XMLBuilder.begin (/Users/thomas/Desktop/forerunner/node_modules/xmlbuilder/lib/XMLBuilder.js:76:15)
    at Object.<anonymous> (/Users/thomas/Desktop/forerunner/execute/xmlt.js:40:5)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

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.