Comprehensive Guide to xml2js An In-Depth Look at XML Parsing and Conversion for Node.js

Introduction to xml2js

xml2js is a powerful Node.js library designed for parsing XML to JavaScript objects and vice versa. It simplifies working with XML data, making it an indispensable tool for developers. In this post, we will explore the various APIs provided by xml2js with detailed explanations and examples.

Installation

  npm install xml2js

Basic Parsing

The most basic task xml2js handles is parsing an XML string to a JavaScript object.

  
    const xml2js = require('xml2js');

    const xml = '<root><child>Hello, World!</child></root>';
    const parser = new xml2js.Parser();

    parser.parseString(xml, (err, result) => {
      if (err) {
        console.error(err);
      } else {
        console.log(result);
      }
    });
  

Customizing Parsing Options

xml2js offers various options to customize parsing according to your needs.

  
    const parser = new xml2js.Parser({ trim: true, explicitArray: false });

    parser.parseString(xml, (err, result) => {
      // Custom parsing logic
    });
  

Building XML from JavaScript Object

You can also convert a JavaScript object back into an XML string using the Builder class.

  
    const builder = new xml2js.Builder();
    const obj = { root: { child: 'Hello, World!' } };
    
    const xml = builder.buildObject(obj);
    console.log(xml);
  

Handling Attributes in XML

To handle attributes in XML, use the ‘attrkey’ option during parsing.

  
    const parser = new xml2js.Parser({ attrkey: 'attributes' });
    const xml = '<root><child attr="value">Hello, World!</child></root>';

    parser.parseString(xml, (err, result) => {
      console.log(result);
    });
  

CDATA Sections

CDATA sections in your XML can be managed as well.

  
    const parser = new xml2js.Parser({ cdata: true });
    const xml = '<root><child><![CDATA[Some  content]]></child></root>';

    parser.parseString(xml, (err, result) => {
      console.log(result);
    });
  

Full Application Example

Let’s put it all together in a sample Node.js application:

  
    const xml2js = require('xml2js');

    const xmlData = '<catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title></book></catalog>';
    const parserOptions = { attrkey: 'attributes', trim: true, explicitArray: false };

    const parser = new xml2js.Parser(parserOptions);
    const builder = new xml2js.Builder();

    parser.parseString(xmlData, (err, result) => {
      if (err) {
        console.error(err);
      } else {
        console.log('Parsed JSON:', result);

        const updatedJson = {
          catalog: {
            book: [
              {
                attributes: { id: 'bk101' },
                author: 'Gambardella, Matthew',
                title: 'XML Developer\'s Guide',
                genre: 'Computer'
              }
            ]
          }
        };

        const updatedXml = builder.buildObject(updatedJson);
        console.log('Updated XML:', updatedXml);
      }
    });
  

xml2js is a versatile library that makes working with XML in Node.js a breeze. With its extensive range of options and user-friendly API, parsing and building XML has never been easier.

Hash: f35dff2468d9bba0f35c08e102944104ea7ff14cf047f92d534042270673839f

Leave a Reply

Your email address will not be published. Required fields are marked *