What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this:

new DOMParser().parseFromString(text,"text/xml");

However, I have encountered a situation where I need to create a copy of the current XMLDocument object in another variable.

My question is: how can I create a deep clone of the parsed XML object?

Thank you for your help!

Answer №1

To create a deep clone of a Node object in JavaScript, you can use the cloneNode(true) method inherited from the Node interface:

var d2 = d.cloneNode(true);

For example:

var d = new DOMParser().parseFromString(
  "<root><x><y></y></x></root>",
  "text/xml"
);
// Prove it's a deep clone by removing `y` from `x`:
console.log("d before", d.documentElement.firstChild.children.length);
var x = d.documentElement.firstChild;
var d2 = d.cloneNode(true);
x.removeChild(x.firstChild);
console.log("d after", d.documentElement.firstChild.children.length);
console.log("d2 after", d2.documentElement.firstChild.children.length);


Eugene Ryabtsev points out that the prolog information from an XML document is not cloned, which is an important consideration.

The prolog information includes:

  • The XML version
  • The standalone flag
  • The encoding

Out of these, only the standalone flag may be relevant. The version is typically 1.0 as per specifications, and the encoding is less pertinent for an in-memory document. However, if you need to preserve the standalone flag, you can manually copy it after using cloneNode:

d2.xmlStandalone = d.xmlStandalone;

This will ensure that the standalone flag is also copied over along with the rest of the Node content.

Answer №2

Don't overcomplicate it, just utilize the power of Serializer along with DOMParser.

duplicateXML=function(xmlData) {
    var stringifiedXML = (new XMLSerializer()).serializeToString(xmlData.getRootNode())
    return new window.DOMParser().parseFromString(stringifiedXML, "text/xml")
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

instructions on how to exclusively close a bracket within a double bracket in a regular expression match

const input = "example(1)(2)example(3)example(4)(5)example(6)(7)example(8)example(9)" const regexp = new RegExp(????) // <-- need help with this input.match(regexp) result: [example(1)(2), example(3), example(4)(5), example(6)(7), example(8), example( ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

Determining the height of a Bootstrap column in relation to another element

Utilizing the grid layout from bootstrap, I have the following structure: <div id="prof_cont_enclose"> <div class="row"> <div class="prof_cont_row"> <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 prof_elem"&g ...

Pagination in DynamoDB: Moving forward and backward through your data

Currently, I am utilizing DynamoDB in combination with NodeJS to display a list of objects on the user interface. Given that DynamoDB can only process 1MB of data at a time, I have opted to implement pagination. This allows users to navigate between pages ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

What is the proper way to activate speech recognition on electron?

I have a chatbot application running on Electron, and I am in need of implementing speech-to-text functionality. I initially tried using window.SpeechRecognition and window.webkitSpeechRecognition, but it seems like Chrome does not support speech recogniti ...

Is it viable to create an onClick event for the text content within a text area?

I'm working on a project that involves displaying XML data in a textarea and creating an onClick event for the content within the textarea. For example: <textarea>Hello Web, This is a simple HTML page.</textarea> My goal here is to create an ...

Updating $data within a VueJS directiveIs there something else you

We have a component and a directive. The structure of our component data is as follows: { langs: [ { title: '', content: '' }, { title: '', content: ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

Showing the information submitted through AngularJS on Node.js with the help of Express

When trying to pass data on the Angular side using a POST method, I encountered an issue. var data = { 'id': mydata.google_id, 'token': mydata.token, 'email': mydata.email, 'name': mydata.name }; $http.po ...

Unexpected memory leaks with ionic during push notification setup leading to system slowdown

Lately, I've been encountering some unusual memory problems that have been persisting for a few days. The issue arises when the app gets stuck and starts rapidly consuming memory until it eventually crashes. During this memory spike, the entire app f ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

An abundance of AJAX requests inundating the server

While working on a straightforward AJAX request, I encountered an issue where the server is sending back 3 responses instead of just one (you can see the example in the attached image). Could someone provide insight into why this might be happening? var ...

Parsing JSON stored in local storage and converting it to a Fabric JS object - JSON generated from form inputs

Currently, I am facing some challenges while using Fabric js for a project that I am working on. My main goal is to create a form where users can input details, which will then be converted into a JSON object and stored locally. After submitting the form, ...

Performing mathematical calculations using javascript

In my project, I'm utilizing HTML, CSS, and JavaScript to achieve the following: Dropdown menu for Category (Coffee Appliance) Dropdown menu for Product (Keurig Coffee Maker) Wattage: 1500kWh (auto-filled from Local Storage) Daily Energy Con ...

What is the best way to link a variable to a specific property within a

I am facing an issue with adding data from the server to a JSON property and displaying it. I know that JSON only accepts primitive types, so how can I dynamically add data to a JSON property? For instance, in the code snippet below, I am trying to assign ...

I must modify the initial statement to appear in bold from the paragraph with the use of JavaScript and CSS

Mr. XYZ and Mrs. ABC are known for their integrity. They own a stylish car. In the next paragraph, I would like to emphasize the first sentence by making it bold, We admire our exceptional leader J.K.L. He shows great potential. In this section, I wan ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...