NODE HELP

xml2js npm (How It Works For Developers)

Published September 29, 2024
Share:

Introduction

Developers may easily incorporate XML data parsing and PDF creation capabilities into their apps by combining XML2JS with IronPDF in Node.js. A well-liked Node.js package called XML2JS makes it easy to transform XML data into JavaScript objects, facilitating programmatic manipulation and use of XML material. Conversely, IronPDF specializes in producing high-quality PDF documents with adjustable page sizes, margins, and headers from HTML, including dynamically created material.

Developers may now dynamically create PDF reports, invoices, or other printable material directly from XML data sources with the help of XML2JS and IronPDF. In order to automate document-generating processes and ensure correctness and flexibility in managing XML-based data for PDF outputs in Node.js applications, this integration makes use of the strengths of both libraries.

What is xml2js?

A Node.js package called XML2JS makes it easier to parse and create a simple XML (Extensible Markup Language) to JavaScript object converter. By offering ways to parse XML files or texts and convert them into structured JavaScript objects, it makes processing XML documents easier. This procedure gives applications freedom in how they interpret and use XML data by providing options for managing XML attributes only, text content, namespaces, merge attributes or keying attributes, and other XML-specific characteristics.

xml2js npm (How It Works For Developers): Figure 1

The library can handle huge XML documents or situations where non-blocking parsing is required because it supports both synchronous and asynchronous parsing operations. Additionally, XML2JS offers mechanisms for validating and resolving errors during the conversion of XML to JavaScript objects, guaranteeing the stability and dependability of data processing operations. All things considered, Node.js applications frequently use XML2JS to integrate XML-based data sources, configure software, change data formats, and streamline automated testing procedures.

XML2JS is a flexible and indispensable tool for working with XML data in Node.js applications because of the following features:

XML Parsing

With the help of XML2JS, developers can more quickly access and handle XML data using the well-known JavaScript syntax by streamlining the processing of XML strings or files into JavaScript objects.

JavaScript Object Conversion

Working with XML data within JavaScript applications is made simple by its smooth conversion of XML data into structured JavaScript objects.

Configurable Options

A variety of configuration options are provided by XML2JS to allow you to alter the way XML data is parsed and converted into JavaScript objects. This covers managing namespaces, text content, attributes, and other things.

Bidirectional Conversion

Round-trip data changes are made possible by its bidirectional conversion capabilities, which enable JavaScript objects to be transformed back into simple XML strings.

Asynchronous Parsing

Large XML documents can be handled well with the library's support for asynchronous parsing processes, which doesn't interfere with the application's event loop.

Error Handling

For the purpose of handling validation problems and parsing mistakes that may arise throughout the XML parsing and transformation process, XML2JS offers strong error-handling methods.

Integration with Promises

It works well with JavaScript Promises, making asynchronous code patterns for handling XML data clearer and easier to handle.

Customizable Parsing Hooks

The flexibility of data processing processes can be increased by developers by creating custom parsing hooks that allow them special options to intercept and alter XML parsing behavior.

Create and Config xml2js

Installing the library and configuring it to meet your needs are the initial steps in using XML2JS in a Node.js application. This is a detailed how-to for setting up and creating XML2JS.

Install XML2JS npm

Make sure that npm and Node.js are installed first. XML2JS may be installed with npm:

npm install xml2js
npm install xml2js
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install xml2js
VB   C#

Basic Usage of XML2JS

This is a simple illustration of how to use XML2JS to parse XML text into JavaScript objects:

const xml2js = require('xml2js');
// Example XML content
const xmlContent = `
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
`;
// Configure XML2JS parser
const parser = new xml2js.Parser();
// Parse XML content
parser.parseString(xmlContent, (err, result) => {
  if (err) {
    console.error('Error parsing XML:', err);
    return;
  }
  console.log('Parsed XML to JavaScript object:', result);
});
const xml2js = require('xml2js');
// Example XML content
const xmlContent = `
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
`;
// Configure XML2JS parser
const parser = new xml2js.Parser();
// Parse XML content
parser.parseString(xmlContent, (err, result) => {
  if (err) {
    console.error('Error parsing XML:', err);
    return;
  }
  console.log('Parsed XML to JavaScript object:', result);
});
const xml2js = require( 'xml2js');
' Example XML content
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: const xmlContent = ` <bookstore> <book category="fiction"> <title> Harry Potter</title> <author> J.K.Rowling</author> </book> <book category="nonfiction"> <title> Thinking, Fast and Slow</title> <author> Daniel Kahneman</author> </book> </bookstore> `;
"fiction"> (Of title) Harry Potter</title> (Of author) J.K.Rowling</author> </book> <book category="nonfiction"> (Of title) Thinking, Fast [and] Slow</title> (Of author) Daniel Kahneman</author> </book> </bookstore> `
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: const xmlContent = ` <bookstore> <book category="fiction"> <title> Harry Potter</title> <author> J.K.Rowling</author> </book> <book category
const xmlContent = ` (Of bookstore) <book category="fiction"> (Of title) Harry Potter</title> (Of author) J.K.Rowling</author> </book> <book category
' Configure XML2JS parser
const parser = New xml2js.Parser()
' Parse XML content
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
parser.parseString(xmlContent, (err, result) =>
If True Then
	If err Then
		console.error( '@Error parsing XML:', err);
		Return
	End If
	console.log( 'Parsed XML @to JavaScript object:', result);
End If
)
VB   C#

xml2js npm (How It Works For Developers): Figure 2

Configuration Options

XML2JS offers a range of configuration options and default settings that let you alter the way parsing behaves. Here's an illustration of how to set default parsing settings for XML2JS:

const xml2js = require('xml2js');
// Example XML content
const xmlContent = `
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
`;
// Configure XML2JS parser with options
const parser = new xml2js.Parser({
  explicitArray: false, // Convert child elements to objects instead of arrays when there is only one child
  trim: true, // Trim leading/trailing whitespace from text nodes
});
// Parse XML content
parser.parseString(xmlContent, (err, result) => {
  if (err) {
    console.error('Error parsing XML:', err);
    return;
  }
  console.log('Parsed XML to JavaScript object with options:', result);
});
const xml2js = require('xml2js');
// Example XML content
const xmlContent = `
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
`;
// Configure XML2JS parser with options
const parser = new xml2js.Parser({
  explicitArray: false, // Convert child elements to objects instead of arrays when there is only one child
  trim: true, // Trim leading/trailing whitespace from text nodes
});
// Parse XML content
parser.parseString(xmlContent, (err, result) => {
  if (err) {
    console.error('Error parsing XML:', err);
    return;
  }
  console.log('Parsed XML to JavaScript object with options:', result);
});
const xml2js = require( 'xml2js');
' Example XML content
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: const xmlContent = ` <bookstore> <book category="fiction"> <title> Harry Potter</title> <author> J.K.Rowling</author> </book> <book category="nonfiction"> <title> Thinking, Fast and Slow</title> <author> Daniel Kahneman</author> </book> </bookstore> `;
"fiction"> (Of title) Harry Potter</title> (Of author) J.K.Rowling</author> </book> <book category="nonfiction"> (Of title) Thinking, Fast [and] Slow</title> (Of author) Daniel Kahneman</author> </book> </bookstore> `
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: const xmlContent = ` <bookstore> <book category="fiction"> <title> Harry Potter</title> <author> J.K.Rowling</author> </book> <book category
const xmlContent = ` (Of bookstore) <book category="fiction"> (Of title) Harry Potter</title> (Of author) J.K.Rowling</author> </book> <book category
' Configure XML2JS parser with options
const parser = New xml2js.Parser({
	explicitArray:= False,
	trim:= True
})
' Parse XML content
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
parser.parseString(xmlContent, (err, result) =>
If True Then
	If err Then
		console.error( '@Error parsing XML:', err);
		Return
	End If
	console.log( 'Parsed XML @to JavaScript object @with options:', result);
End If
)
VB   C#

Handling Asynchronous Parsing

Asynchronous parsing is supported by XML2JS , which is useful for managing big XML documents without stopping the event loop. Here's an illustration of how to use async/await syntax with XML2JS:

const xml2js = require('xml2js');
// Example XML content (assume it's loaded asynchronously, e.g., from a file)
const xmlContent = `
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
`;
// Configure XML2JS parser
const parser = new xml2js.Parser();
// Async function to parse XML content
async function parseXml(xmlContent) {
  try {
    const result = await parser.parseStringPromise(xmlContent);
    console.log('Parsed XML to JavaScript object (async):', result);
  } catch (err) {
    console.error('Error parsing XML (async):', err);
  }
}
// Call async function to parse XML content
parseXml(xmlContent);
const xml2js = require('xml2js');
// Example XML content (assume it's loaded asynchronously, e.g., from a file)
const xmlContent = `
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
`;
// Configure XML2JS parser
const parser = new xml2js.Parser();
// Async function to parse XML content
async function parseXml(xmlContent) {
  try {
    const result = await parser.parseStringPromise(xmlContent);
    console.log('Parsed XML to JavaScript object (async):', result);
  } catch (err) {
    console.error('Error parsing XML (async):', err);
  }
}
// Call async function to parse XML content
parseXml(xmlContent);
Private const xml2js = require( 'xml2js');
' Example XML content (assume it's loaded asynchronously, e.g., from a file)
Private const xmlContent = ` (Of bookstore) <book category="fiction"> (Of title) Harry Potter</title> (Of author) J.K.Rowling</author> </book> <book category="nonfiction"> (Of title) Thinking, Fast [and] Slow</title> (Of author) Daniel Kahneman</author> </book> </bookstore> `
' Configure XML2JS parser
Private const parser = New xml2js.Parser()
' Async function to parse XML content
Async Function parseXml(ByVal As xmlContent) As [function]
  Try
	const result = Await parser.parseStringPromise(xmlContent)
	console.log( 'Parsed XML @to JavaScript object(async):', result);
  Catch e1 As err
	console.error( '@Error parsing XML(async):', err);
  End Try
End Function
' Call async function to parse XML content
parseXml(xmlContent)
VB   C#

Getting Started

In order to use IronPDF and XML2JS in a Node.js application, you must first read XML data and then create a PDF document from the content that has been processed. This is a detailed how-to that will assist you in installing and configuring these libraries.

What is IronPDF?

The IronPDF library is a potent Node.js library for working with PDFs. The goal of it is to convert HTML content into PDF documents with exceptional quality. It streamlines the process of turning HTML, CSS, and other JavaScript files into properly formatted PDFs without compromising the original online content. This is a very useful tool for web applications that need to produce dynamic, printable documents such as invoices, certifications, and reports.

IronPDF has several features, including customizable page settings, headers, footers, and the ability to insert fonts and images. It supports complex layouts and styles to ensure that all the test output PDFs follow the specified design. Moreover, IronPDF controls JavaScript execution within HTML, allowing for accurate rendering of dynamic and interactive content.

xml2js npm (How It Works For Developers): Figure 3

Features of IronPDF

PDF Generation from HTML

Convert HTML, CSS, and JavaScript to PDF. Supports two modern web standards: media queries and responsive design. Helpful for using HTML and CSS to dynamically decorate PDF invoices, reports, and documents.

PDF Editing

It is possible to add text, images, and other material to already-existing PDFs. Extract text and images from PDF files. Merge many PDFs into a single file. Split PDF files up into several distinct papers. Add headers, footers, annotations, and watermarks.

Performance and Reliability

In industrial contexts, high performance and reliability are desirable design attributes. Easily handles large document sets.

Install IronPDF

To gain the tools you need to work with PDFs in Node.js projects, install the IronPDF package.

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install @ironsoftware/ironpdf
VB   C#

Parse XML and Generate PDF

To illustrate, let us generate a basic XML file called example.xml:

<!-- example.xml -->
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
<!-- example.xml -->
<bookstore>
  <book category="fiction">
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book category="nonfiction">
    <title>Thinking, Fast and Slow</title>
    <author>Daniel Kahneman</author>
  </book>
</bookstore>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<!-- example.xml -- > <bookstore> <book category="fiction"> <title> Harry Potter</title> <author> J.K.Rowling</author> </book> <book category="nonfiction"> <title> Thinking, Fast @and Slow</title> <author> Daniel Kahneman</author> </book> </bookstore>
VB   C#

Create the GeneratePdf.js Node.js script, which reads the XML file, uses XML2JS to parse it into a JavaScript object, and then uses IronPDF to create a PDF from the resulting object of parsed data.

// generatePdf.js
const fs = require('fs');
const xml2js = require('xml2js');
const IronPdf = require("@ironsoftware/ironpdf");
const fs = require('fs');
const document=IronPdf.PdfDocument;
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
// Function to read and parse XML
parseXml=async (filePath)=> {
  const parser = new xml2js.Parser();
  const xmlContent = fs.readFileSync(filePath, 'utf8');
  return awaitparser.parseStringPromise(xmlContent);
}
// Function to generate HTML content from the parser object
function generateHtml(parsedXml) {
  let htmlContent = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Bookstore</title>
      <style>
        body { font-family: Arial, sans-serif; }
        .book { margin-bottom: 20px; }
      </style>
    </head>
    <body>
      <h1>Bookstore</h1>
  `;
// root node mapping
  parsedXml.bookstore.book.forEach(book => {
    htmlContent += `
      <div class="book">
        <h2>${book.title}</h2>
        <p><strong>Category:</strong> ${book.$.category}</p>
        <p><strong>Author:</strong> ${book.author}</p>
      </div>
    `;
  });
  htmlContent += `
    </body>
    </html>
  `;
  return htmlContent;
}
// Main function to generate PDF
generatePdf=async()=> {
  try {
    var parser = await parseXml('./example.xml');
    const htmlContent = generateHtml(parser);
    document.fromHtml(htmlContent).then((pdfres)=>{
        const filePath = `${Date.now()}.pdf`;
          pdfres.saveAs(filePath).then(()=>{
            console.log('PDF saved successfully!');
         }).catch((e)=>{
            console.log(e);
         });
        });
  } catch (error) {
    console.error('Error:', error);
  }
}
// Run the main function
generatePdf();
// generatePdf.js
const fs = require('fs');
const xml2js = require('xml2js');
const IronPdf = require("@ironsoftware/ironpdf");
const fs = require('fs');
const document=IronPdf.PdfDocument;
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
// Function to read and parse XML
parseXml=async (filePath)=> {
  const parser = new xml2js.Parser();
  const xmlContent = fs.readFileSync(filePath, 'utf8');
  return awaitparser.parseStringPromise(xmlContent);
}
// Function to generate HTML content from the parser object
function generateHtml(parsedXml) {
  let htmlContent = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Bookstore</title>
      <style>
        body { font-family: Arial, sans-serif; }
        .book { margin-bottom: 20px; }
      </style>
    </head>
    <body>
      <h1>Bookstore</h1>
  `;
// root node mapping
  parsedXml.bookstore.book.forEach(book => {
    htmlContent += `
      <div class="book">
        <h2>${book.title}</h2>
        <p><strong>Category:</strong> ${book.$.category}</p>
        <p><strong>Author:</strong> ${book.author}</p>
      </div>
    `;
  });
  htmlContent += `
    </body>
    </html>
  `;
  return htmlContent;
}
// Main function to generate PDF
generatePdf=async()=> {
  try {
    var parser = await parseXml('./example.xml');
    const htmlContent = generateHtml(parser);
    document.fromHtml(htmlContent).then((pdfres)=>{
        const filePath = `${Date.now()}.pdf`;
          pdfres.saveAs(filePath).then(()=>{
            console.log('PDF saved successfully!');
         }).catch((e)=>{
            console.log(e);
         });
        });
  } catch (error) {
    console.error('Error:', error);
  }
}
// Run the main function
generatePdf();
' generatePdf.js
const fs = require( 'fs');
const xml2js = require( 'xml2js');
const IronPdf = require("@ironsoftware/ironpdf")
const fs = require( 'fs');
const document=IronPdf.PdfDocument
Dim config=IronPdf.IronPdfGlobalConfig config.setConfig({licenseKey: ''});
' Function to read and parse XML
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'parseXml=async(filePath)=>
'{
'  const parser = New xml2js.Parser();
'  const xmlContent = fs.readFileSync(filePath, 'utf8');
'  Return awaitparser.parseStringPromise(xmlContent);
'}
' Function to generate HTML content from the parser object
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@function generateHtml(parsedXml)
'{
'  let htmlContent = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> Bookstore</title> <style> body
'  {
'	  font-family: Arial, sans-serif;
'  }
'		.book
'		{
'			margin-bottom: 20px;
'		}
'	  </style> </head> <body> <h1> Bookstore</h1> `;
'' root node mapping
'  parsedXml.bookstore.book.forEach(book =>
'  htmlContent += ` </body> </html> `;
'  Return htmlContent;
'}
' Main function to generate PDF
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'generatePdf=async()=>
'{
'  try
'  {
'	var parser = await parseXml('./example.xml');
'	const htmlContent = generateHtml(parser);
'	document.fromHtml(htmlContent).@then((pdfres)=>
VB   C#

An easy way to convert XML data and parse multiple files into PDF documents is to combine IronPDF and XML2JS in a Node.js application. Using XML2JS, the XML content of multiple files is parsed into a JavaScript object once the XML file is first read using the fs module of Node.js. Subsequently, the HTML text that forms the foundation of the PDF is dynamically generated using this processed data.

The script begins by reading XML text from a file and using xml2js for to parse it into a JavaScript object. From the parsed object of data, a custom function creates HTML content, structuring it with the required elements—for example, authors and titles for a bookstore. This HTML is subsequently rendered into a PDF buffer using IronPDF. The produced PDF is then saved to the file system.

xml2js npm (How It Works For Developers): Figure 4

Using IronPDF's effective HTML-to-PDF conversion and XML2JS's robust XML parsing capabilities, this method offers a simplified way to create PDFs from XML data in Node.js applications. The connection makes it possible to turn dynamic XML data into PDF documents that are printable and well-formatted. This makes it perfect for applications that require automated document generation from XML sources.

xml2js npm (How It Works For Developers): Figure 5

Conclusion

To sum up, XML2JS and IronPDF together in a Node.js application provide a strong and adaptable way to turn XML data into high-quality PDF documents. Effective XML parsing into JavaScript objects using XML2JS makes data extraction and manipulation simple. After the data has been parsed, it can be dynamically changed into HTML text, which IronPDF can then easily convert into properly structured PDF files.

Applications requiring the automated creation of documents like reports, invoices, and certificates from XML data sources may find this combination especially helpful. Developers can ensure accurate and aesthetically pleasing PDF outputs, streamline workflows, and improve the ability of Node.js apps to handle document-generating tasks by utilizing the benefits of both libraries.

IronPDF offers developers more capabilities along with more efficient development, all while utilizing Iron Software's highly flexible systems and suite.

It is easier for developers to choose the best model when license options are explicit and specific to the project. These features let developers solve a variety of problems in an easy-to-use, efficient, and cohesive way.

< PREVIOUS
LoopBack node js (How It Works For Developers)
NEXT >
replicate npm (How It Works For Developers)

Ready to get started? Version: 2024.11 just released

Free npm Install View Licenses >