Generating XML attribute through XPath

How can I create an XML attribute using XPath to find the element I want to add the query on?

For example:

const xmlText = `<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title id="somethingeng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>`;

var doc = new DOMParser().parseFromString(xmlText,'text/xml');

var r = doc.evaluate("//*[@lang[contains(.,'eng')]]", doc, null, XPathResult.ANY_TYPE, null);

I am looking to define an attribute for this 'r'.

Answer №1

Initially, the xmlText string needs to be converted into a template literals format with new lines included.

evaluate() seemed adequate, but the outcome is an XPathResult requiring iteration using XPathResult.iterateNext().

const xmlText = `<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title id="somethingeng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>`;

var doc = new DOMParser().parseFromString(xmlText,'text/xml');

var r = doc.evaluate("//*[@lang[contains(.,'eng')]]", doc, null, XPathResult.ANY_TYPE, null);

var next = r.iterateNext();
while (next) {
  console.log(next.textContent);
  next = r.iterateNext();
}

Modification

Considering the iterator, it's essential to gather the nodes of interest and then make modifications afterward. Below are functions created for generating child elements and attributes based on an XPath expression and an object representing the new data.

const xmlText = `<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title id="somethingeng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>`;

var doc = new DOMParser().parseFromString(xmlText, 'text/xml');

function addAttribute(doc, xpath, obj) {
  let r = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null);

  let nodes = [];
  let next = r.iterateNext();
  while (next) {
    nodes.push(next);
    next = r.iterateNext();
  }

  nodes.forEach(node => {
    Object.keys(obj).forEach(key => {
      let newattr = doc.createAttribute(key);
      newattr.value = obj[key];
      node.setAttributeNode(newattr);
    });
  });
}

function addChildNode(doc, xpath, obj) {
  let r = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null);

  let nodes = [];
  let next = r.iterateNext();
  while (next) {
    console.log(next.textContent);
    nodes.push(next);
    next = r.iterateNext();
  }

  nodes.forEach(node => {
    Object.keys(obj).forEach(key => {
      let newnode = doc.createElement(key);
      newnode.textContent = obj[key];
      node.appendChild(newnode);
    });
  });
}



addAttribute(doc, "//title[@lang[contains(.,'eng')]]", {"data-lang":"eng", index: 2});
addChildNode(doc, "//book[number(price) < 30]", {sale: true});

console.log(doc.documentElement.outerHTML);

Answer №2

Successfully resolved the issue utilizing XPathResult.snapshotItem().

var xmlText = `<?xml version="1.0" encoding="ISO-8859-1"?>
  <bookstore>
    <book>
      <title lang="eng">Harry Potter</title>
      <price>29.99</price>
    </book>
    
    <book>
      <title id=\"somethingeng\">Learning XML</title>
      <price>39.95</price>
    </book>
    
  </bookstore>`;

var doc = new DOMParser().parseFromString(xmlText, 'text/xml');
var r = doc.evaluate("//*[@id[contains(.,'eng')]]", doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

var index = 0;
while (index < r.snapshotLength) {
  var next = r.snapshotItem(index);
  next.setAttribute("value", "val");
  index++;
}

var xmlSerializer = new XMLSerializer();
const updatedDoc = xmlSerializer.serializeToString(doc);

console.log(updatedDoc);

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

Encountering a dependency tree error while attempting to install generic-ui with npm

While attempting to add generic-ui to my Angular project using the command: npm i @generic-ui/ngx-grid @generic-ui/fabric @generic-ui/hermes I encountered the following error : $ npm i @generic-ui/ngx-grid @generic-ui/fabric @generic-ui/hermes npm ERR! co ...

What is the best way to retain the href value following a link click event?

Is it possible for a user's clicked link on another site to be saved, so that the href value can be used in another function upon returning to the client's site? For example, if I click on the client's logo on another site and am redirected ...

Dynamically alter the field ID using JavaScript

I have a checkbox and a label for the checkbox that is actually coded as another field: <td style="text-align:left; width:210px; font-size:11px; height:20px;vertical-align:middle; " colspan="2" > <asp:CheckBox ID="Strengthx" runat="se ...

Identifying the web browser by utilizing the UserAgent detection method

How can I determine if the current browser is Chrome using TypeScript/JavaScript? I previously used the following method: var isChrome = !!(<any>window).chrome && !!(<any>window).chrome.webstore; However, this doesn't work anymo ...

I strive to establish a strong link between React and Firebase

I am facing an issue with Firebase and React. The problem arises after clicking on my add-data button to insert data into the database. Below is the error message I receive in the console: Reference_impl.ts:482 Uncaught TypeError: db._checkNotDeleted ...

Creating personalized markers in Angular using Google Maps Icon customization

Having trouble displaying a custom icon instead of the default one on my map. html <ui-gmap-google-map center="vm.map.center" zoom="vm.map.zoom" options="options"> <ui-gmap-marker icon="vm.options.icon" coords="vm.marker.coords" events="vm.marke ...

Adjust the interval scope within an AngularJS directive to set up a loop

Within my agnularjs directive, I have an object containing the logic of a script: $scope.slider = { increment: 0, step: 1, positionTop: 0, init: function (step, isClick) { if(isClick) clearInterval($scope.interval); ...rest ...

Utilize Google Place Autocomplete to restrict input to only addresses recommended by autocomplete suggestions

My application includes an input field for users to enter an address, with the help of Google's Place Autocomplete feature for address suggestions. The location field is mandatory. I aim to restrict users from submitting the form with an address that ...

Dealing with textarea in Javascript

I am new to JavaScript and facing a challenge in creating a delimited string from a textarea input. The issue is that when the textarea is passed in, it includes newlines for each row. I aim to parse the entire textarea content into a string with a delimit ...

Ways to allocate space evenly between components of the same size in React Native

As a beginner in Javascript and React-native, I have been experimenting with the technology to assess its viability for potential use in my current workplace. However, I have encountered some challenges with the user interface. To enhance my understanding ...

I can't seem to get the npm run dev command to work properly after setting up

After successfully setting up React JS with Vite and running npm i, I encountered an error when trying to run npm run dev: > [email protected] dev > vite E:\nasheednaldo\node_modules\rollup\dist\native.js:64 ...

What is the best way to simulate a service that returns a promise when writing unit tests for AngularJS using Jasmine?

I have a service named myService that relies on another service called myOtherService. The latter makes a remote call and returns a promise. Here's the implementation: angular.module('app.myService', ['app.myOtherService']) .fac ...

Angular does not have the capability to automatically update itself

I have developed an angular project that includes a navigation bar. I would like the navigation bar to automatically update when users log in. I tried using ng-show and ng-hide to control it, but unfortunately, it doesn't seem to work. Can someone hel ...

Make changes to an xml file using c# and then ensure to save the updated

I am working with an XML file that contains image URLs. My task is to check if the URL is responsive and, if it's not, remove it from the XML file before saving all changes. However, I am encountering an error message that says: 'The process c ...

What is the proper way to convert the date and time of Friday, October 23, 2015 at midnight into a specific format for a datetime string?

I'm currently utilizing the bootstrap datetimepicker and I need to retrieve the datetime and then add days to it. var get_date_time = Friday, October 23rd 2015, 12:00:00 am I want to format get_date_time to "Oct 25 2015 12:00:00 am", but I'm u ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...

Determine whether any element in the array matches a property of the object

Let's start with an array: arr=[ "EMPRESA", "CD_DIRECAO", "DT_INI_DIRECAO" ] Next, we have an object: primary = { "EMPRESA": {"type": "varchar"}, "CD_DIRECAO": {"type": "varchar"}, "DT_INI_DIR ...

Function for calling a CSS callback with jQuery

I am currently working on enhancing my search bar using jQuery, and I am also looking to hide the navigation links. Here is a snippet of the jQuery code I have been using. The code functions properly when focused. $(".searchBox input").focus(function(){ ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

What could be causing my code to output [object Object] instead of an array in node.js?

I've been working on building a website using Node.js to make API calls and populate information. On the homepage, I have a sidebar where users can filter by different 'categories'. However, when I run my code, instead of displaying the cate ...