Leverage JavaScript E4X to cleverly rename specific XML elements

Currently, I am using JavaScript to manipulate XML without involving the DOM in a browser context. I need assistance with creating an E4X expression that can rename a list of tags based on a given substring. The challenge is that I may not know the exact tag names beforehand.

Here is a hypothetical scenario:

someXML = <Favourites>
              <JillFaveColour>Blue</JillFaveColour>
              <JillFaveCandy>Smarties</JillFaveCandy>
              <JillFaveFlower>Rose</JillFaveFlower>
          <Favourites>

My objective is to transform the XML into:

<Favourites>
    <GaryFaveColour>Blue</GaryFaveColour>
    <GaryFaveCandy>Smarties</GaryFaveCandy>
    <GaryFaveFlower>Rose</GaryFaveFlower>
<Favourites>

The catch is that the number of tags can vary and their full names are unknown. They should only be renamed if they contain a specific substring (in this case, "Jill").

Answer №1

To change the name of elements, you can use the setLocalName(newName) method. If you are unsure of all the tag names in advance, you can loop through the elements and access their tag names using the localName() method (only if

node.length() === 1 && node.nodeKind() === "element"
).

Answer №2

For example:

let animals = someData.animals();
for (let i = animals.length; i-->0;)
    if (animals[i].type==='dog')
        animal.setName(animal.name().split('Buddy').join('Max'));

Answer №3

Have you thought about manually adding and then removing those nodes?

//xmlObj represents your XML object
xmlObj['Favorites']['JohnFavoriteColor'] = xmlObj['Favorites']['JaneFavoriteColor'];
xmlObj['Favorites']['JohnFavoriteFood'] = xmlObj['Favorites']['JaneFavoriteFood'];
xmlObj['Favorites']['JohnFavoriteAnimal'] = xmlObj['Favorites']['JaneFavoriteAnimal'];

//delete Jane's favorites
delete xmlObj['Favorites']['JaneFavoriteColor'];
delete xmlObj['Favorites']['JaneFavoriteFood'];
delete xmlObj['Favorites']['JaneFavoriteAnimal'];

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

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

Having difficulties accessing information from the HTML document

I face an issue with my code where I am unable to fetch the sectionID from tr. I want to retrieve the dynamic id of sectionID on each button click for deletion, but it always returns null. Below is the JQuery script: <script> $(function () { $(&apo ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Discovering if an agent is a mobile device in Next.js

I am currently working with nextjs version 10.1.3. Below is the function I am using: import React, {useEffect, useState} from "react"; const useCheckMobileScreen = () => { if (typeof window !== "undefined"){ const [widt ...

There was an issue with the NextJS axios request as it returned a status code

I'm currently in the process of developing an application with NextJS and Strapi In my project, I am fetching data from Strapi using Axios within NextJS Next: 14.0.4 Axios: ^1.6.5 Strapi: 4.17.1 Node: 18.17.0 Here is the code snippet: import axios f ...

Employ a for loop to generate custom shapes within the canvas

EDIT: I will be sharing all of my code including the HTML and JS. Pardon me for the abundance of comments. I am attempting to generate rectangles in a canvas using a for loop (taking user input) and then access them in another function to perform certain ...

It appears that the SignalR proxy is not defined

Why is $.connection.connectionhub showing as undefined? I am using webform. <script src="/scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library. --> <script src="/scripts/jquery.signalR-2.2.1.min.js">< ...

The medium-zoom feature is currently experiencing issues with functionality within Angular version 13

I've been attempting to incorporate medium-zoom functionality into my project using https://www.npmjs.com/package/medium-zoom Here are the steps I took: ng new medium_zoom_test (Angular 13) with routing & css npm install medium-zoom The image is ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

How can I make TypeScript properly export function names for closure-compiler?

Here is the TypeScript code I am working with: namespace CompanyName.HtmlTools.Cookie { export function eraseCookie(name:string, path:string) { createCookie(name, "", path, -1); } export function readCookie(name:string) { ...

Looking to enhance the accessibility of a dynamically generated file by implementing the ability to expand and collapse sections as parent nodes

Currently working on a webpage where I am showcasing a testsuite file as the parent node and test cases within the testsuite file as child nodes. I have added checkboxes to both the parent and child nodes. Now, my goal is to include an ex ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

Tips for efficiently rendering over 200 views in React Native without sacrificing performance

I've been working on a game project using react-native and I'm facing an issue with rendering over 200 views on the Game screen. Each view should have a pressable functionality that, when pressed, will change the background color of the view and ...

Ways to implement a delay in a function?

I'm looking for a way to introduce a delay in my function. Should I enclose the function within a delay function, or is there a different method to ensure that the animation doesn't trigger until 5 seconds after the page has loaded? var textTo ...

The act of initiating a click on a radio button involves evaluating conditions prior to toggling

Apologies for the slightly ambiguous title, let me provide a clearer explanation. I have created a codepen to demonstrate an issue that I am facing. You can view it here. In my codepen, I have two toggle buttons labeled "Male" and "Female" for simplicity. ...