Eliminate full stops from within the XML elements

I encountered a strange issue where the XML files contain periods (.) within them.

<member>
    <name>ABCD</name>
        <value>         
             <date.of.birth>02.05.2000</date.of.birth>
        </value>                        
</member>

As a result, I am facing difficulty parsing the XML in javascript. I typically convert this XML into JSON and utilize JSON.parse().

If you have any insights on how to efficiently replace all periods in XML Tags with an underscore or another character using Javascript, please share your expertise. Here is an example of what I am looking for:

<member>
    <name>ABCD</name>
        <value>         
                <date_of_birth>02.05.2000</date_of_birth>
        </value>                        
</member>

Thank you in advance.

Answer №1

To achieve parsing, one can utilize pure JavaScript:

var content = '<?xml version="1.0" encoding="UTF-8"?><member><name>ABCD</name><value><date.of.birth>02.05.2000</date.of.birth></value></member>';

if (window.DOMParser)
{
  var parser = new DOMParser();
  var xmlDoc = parser.parseFromString(content, "application/xml");
}
else // For Internet Explorer
{
  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(content);
}

// Accessing DOM elements:
var element = xmlDoc.getElementsByTagName('date.of.birth')[0];

To replace a tag, the following code can be used:

var newElement = xmlDoc.createElement('date_of_birth');
newElement.innerHTML = element.innerHTML;
element.parentNode.insertBefore(newElement, element);
element.parentNode.removeChild(element);

// Displaying the updated XML document
xmlDoc

Update:

To dynamically find elements with a specific tag name, you can use the following approach:

 var allElements = xmlDoc.getElementsByTagName("*"); // Get all elements
 var filteredElements = [];
 for(var j=0; j < allElements.length; j++)
 { 
   if ( /\./.test(allElements[j].tagName) ) // Filter by our criteria
   { 
     filteredElements.push(allElements[j]);
   } 
 }
 filteredElements // Contains the expected elements

Answer №2

Using JavaScript

It may not be as straightforward to accomplish this task using vanilla JavaScript.

Update: Check out JavaScript: how to modify tag name?

Using XML

On the other hand, achieving this in XML is much simpler. All you have to do is match the dot-named tags with an xml:template and reassign it a custom name.

<xml:template match="date.of.birth">
  <xml:element name="replace(local-name(), '.', '_')">
    <xml:value-of select="./text()" />
  </xml:element>
</xml:template>

In this example, I am generating an xml:element based on the original name where I substitute any instances of a . (dot) with an underscore _.

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

Utilizing Matrix Distance Genetic Algorithm for Mobile Applications

I am working on an Android routing application that allows users to input travel time in hours, and my app generates possible routes for them. To determine the routes, I am using a genetic algorithm (GA) implemented in PHP. However, I face a challenge reg ...

Retrieve the innerHtml value of an asp.net Label using C# programmatically

I have a JavaScript function that successfully retrieves the cursor position value. I am assigning this value to an ASP.NET label's innerHTML property. How can I access this innerHTML property when a treeview_selectednodechange event occurs in my prog ...

What is the correct way to link to a SCSS file within a component's directory?

The structure of my directories is as follows: stylesheets ..modules ...._all.scss ...._colors.scss ..partials ...._all.scss ...._Home.scss ..main.scss In the _Home.scss file, I have the following: @import '../modules/all'; .headerStyle { c ...

Guide to implementing event handling with JavaScript on an HTML form webpage

On my HTML page, I have a PHP extension file named 'welcome.php'. Within this page, there is a button labeled "baggage.php" that, when clicked, opens another page. On this new page, I have created dropdown menus for 'From' and 'To& ...

Unusual problem arises with styling and element measurement (scrollWidth / scrollWidth) in Gatsby framework

Currently, I am working on a component that splits lines based on the parent container's width without overflowing. Despite successfully implementing this in a sandbox or pure react application (even with custom fonts), I encountered issues when using ...

Having trouble implementing styles for an element selected using the document.getElementsByClassName() method

In order to adjust the style of a dropdown menu, I need to change its top value to align it properly. The element is being generated by Drupal (a CMS tool) and is configured with classes for styling purposes in the admin view where content is authored. How ...

What is the best way to trigger the afterRender handler function within a nested foreach loop?

One of the challenges I encountered was using a foreach statement along with afterRender to trigger a specific function. <div data-bind="foreach: { data: Object.keys(pricings()), as: '_propkey', afterRender: pricingTableRenderedHandler }& ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Display all items with pagination in a Material UI Table using React

I have recently implemented pagination in a react data table to handle a large number of entries. I wanted to add an option to display all entries by selecting "all" in the rowsPerPageOptions dropdown menu. Currently, I am able to show the count of all ent ...

How to extract only the value from a MongoDB query using NodeJS

Currently, I am attempting to extract just the value of a specific field from a MongoDB document using the following code: var collection = db.collection('people'); collection.find({"name" : "John" }, { phone : 1, _id : 0 }).toArray(function (e ...

Obtaining XML data is possible using the "Postman software," however, accessing data through SWIFT is proving to be a challenge

When using Postman, I am able to retrieve XML data from the following link: View Postman image However, after following a tutorial on parsing XML data using SWIFT language, I encountered an issue where the URL was considered "invalid". SWIFT parsing url c ...

Establishing the maximum width of a Vuetify expansion panel component

https://i.sstatic.net/QqKVv.png I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansio ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

HTML5 enables users to pick their preferred font style

In my JavaScript and HTML5 course, I am working on developing a website where users can choose the background color and decide between using SANS SERIF or SANS fonts. The background color selection feature is already functioning successfully -- var inputC ...

How can I construct a Query Builder expression in Laravel that involves selecting from 2 different tables?

I am struggling with translating this SQL query to a query builder syntax: select products.* from orders, json_table( orders.order_summary, "$.products[*]" columns( quantity int path "$.quantity", variant_id int path ...

Display different data in an HTML table for each individual click on the "Read more" event

I am currently extracting data from a SQL table to exhibit it in an HTML table. The issue I am facing is that I would like to implement a "Read More" feature to prevent clutter in the table. As I am retrieving the data row by row, I am utilizing a class n ...

How to assign an enum value to a JSON object in an Angular application

I am currently dealing with a scenario where I have a constant requestBody object being defined. It contains various properties like clientId, orderingId, receivedSignatureFlag, saturdayDeliveryFlag, and so on. const requestBody: RequestBody = { clientId ...

Strategies for structuring CoreData to manage intricate datasets

I am faced with the task of storing JSON data locally using CoreData, which is retrieved from an API call. The challenge lies in the complexity of the JSON structure, as it consists of a main Dictionary with 4 keys, each key containing further nested Dict ...

Embedding a stylesheet into an HTML document can be done automatically

Currently, I am working on creating standalone error pages (404/503) as individual HTML files. My server-side setup involves Node.js, but these specific files will be hosted directly in Nginx. One of the challenges I am facing is automatically including a ...

Differences between functions in Angular services and components: which one to use?

Our Angular application is made up of excel-like grids, with 20 components each containing a unique grid. Every component includes a save() function that handles adding, editing, and deleting items. The save() function is quite large and resides in each c ...