Exploring the capabilities of using XPath with a DOM document

I've been attempting to locate an xml node using an xpath query, but I'm having trouble getting it to work. When I try in Firefox, the result is always "undefined" and Chrome throws an error code.

<script type="text/javascript">

var xmlString = '<form><name>test</name></form>';
var doc = new DOMParser().parseFromString(xmlString,'text/xml');

var result = doc.evaluate('/form/name', doc, 
                          null, XPathResult.ANY_TYPE, null);

alert(result.stringValue);

</script>

Can anyone help me identify what's wrong with this code?

Answer №1

It's unclear why you encountered this error, but changing from XPathResult.ANY_TYPE to XPathResult.STRING_TYPE should resolve it (tested in firefox 3.6).

Consider the following:

var xmlString = '<form><name>test</name></form>';
var doc = new DOMParser().parseFromString(xmlString,'text/xml');
var result = doc.evaluate('/form/name', doc, null, XPathResult.STRING_TYPE, null);
alert(result.stringValue); // returns 'test'

View on jsfiddle.


EXPLANATION:

The 4th parameter of the evaluate method is an integer that specifies the desired result type (reference). There are different types, such as integer, string, and any type. The method returns an XPathResult, which has various properties.

You need to match the property (numberValue, stringValue) with the one used in evaluate.

It's puzzling why using any type didn't work with string value.

Answer №2

XPathResult.ANY_TYPE will yield a node set for the xpath expression /form/name, making it difficult to convert the node set to a string using result.stringValue. In such cases, you can utilize result.iterateNext().textContent

On the other hand, if the expression is something like count(/form/name), it will produce a numerical value when utilized with XPathResult.ANY_TYPE, allowing you to retrieve the number using result.numberValue.

For further in-depth explanation, visit https://developer.mozilla.org/en/DOM/document.evaluate#Result_types

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

Achieve iframe resizing using only pure JavaScript, no reliance on jQuery required

I have a question about an iframe on my webpage. <iframe class="myframe" src="some_page.html" width="800px" height="600px" /> Is there a way to make this iframe resizable like the <textarea></textarea> tag? I prefer to achieve this wit ...

Exploring JavaScript Unit Testing: Essential dependencies for testing with Karma, jasmine, and bootstrap

After creating an application using AngularJS and additional tools based on bootstrap, I am now facing the challenge of testing everything. However, there seems to be a problem with Karma and Jasmine as an exception is thrown when running the tests. The i ...

Using AJAX to populate a dropdown menu with an array in PHP

I am working on a functionality where I have two drop-down boxes. The first one should select the category, triggering an AJAX call to a PHP file that fetches the appropriate subcategory array and populates the second drop-down. Check out the code snippet ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

determine the vertical dimension of the horizontal scrollbar

I ran into an issue where I needed to determine the height of a horizontal scrollbar. This question and answer recommended using the clientHeight property to calculate the difference. Unfortunately, this method no longer works as shown here: https://jsfid ...

When you input text into a contenteditable div, it automatically gets placed inside a span element instead of being placed

I'm having an issue with my contenteditable div. Whenever I click the button, a span is inserted into the div. However, when I start typing, the text goes inside the span instead of outside it: jQuery(document).ready(function($) { let input = $(" ...

Using a jQuery function to conceal a column in a web grid

I am currently using asp .net MVC3 to create a hover effect on selected columns. On a page, there is a grid, Multiselect Listbox, and a button. To display the table, I am utilizing the following webgrid: @{ var grid = new WebGrid(Model.oTravelReadyEntit ...

Show validation messages using ng-messages depending on various conditions

Implementing angular ng-messages for validation message display Check out this code snippet: <ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple> <li ng-message="pattern">Invalid pattern</li> <li ng-m ...

Customizing Column Background Color with AngularJS

https://i.sstatic.net/OHFFF.png My current webapp highlights the day of the week on a table for the current day and the day two weeks from now. However, I'm facing an issue with adjusting the highlight if either of these days falls on a holiday. Curr ...

Please ensure that the RelativeLayout element is properly declared

I am encountering an error that says "element RelativeLayout must be declared," and I am unsure of why this error is happening. Can anyone provide suggestions or code snippets on how to resolve this issue? Below is code from my drawer_list_item.xml < ...

Removing an item from an array stored in jQuery using the .data() method

Utilizing the .data() method in jQuery, I have saved an array as shown below: var myArray = {}; myArray[0] = {}; myArray[0][0] = "test00"; myArray[0][1] = "test01"; myArray[1] = {}; myArray[1][0] = "test10"; myArray[1][1] = "test11"; $('#datastorage ...

What is the reason behind Vue not updating the array order in $ref when unshift is used?

Here's an interesting example to ponder: <template> <div> <button @click="addItem">Add Item</button> <h1>Fruits</h1> <ul> <li v-for="(item, index) in items" ...

Is there a way to effortlessly zoom in on a Google map with just one mouse click?

Can the Google Maps be zoomed to a specific level with just one click of the mouse? ...

Encountering an error when trying to execute JavaScript in Node: Uncaught SyntaxError - An unexpected identifier was found

Although the code below works perfectly fine in a browser, I encountered an error when trying to run it via node (in the command prompt) which reads: Uncaught SyntaxError: Unexpected identifier Please refer to the attached screenshot for details. //inde ...

Dealing with Failed Axios Requests in React

I'm having trouble figuring out what I'm doing incorrectly. My goal is for the Main component to pass the ajax request method to the child component InputForm. The child component would then return the results, which will be stored in the state ...

org.openqa.selenium.WebDriverException: unexpected issue: Chrome failed to initiate: crashed.(chrome inaccessible)

Having issues running Java script (selenium framework) on Chrome. Tried various solutions but still facing problems: Unchecked run as admin Added arguments Snippet of the code: ChromeOptions options = new ChromeOptions(); //options.setExperimentalOption ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

Choose all the inputs with the value attribute specified

How can I select all input textboxes in my form that have the required class and no value using jQuery? Currently, I am using: $('input[value=""]', '.required') The issue I am facing is that even when a user enters a value in the text ...

Upon selecting a hyperlink, the function's value ought to be saved within a text box

Some programming languages I'm working with are PHP, Javascript, and HTML I've created a PHP function that is stored in page2.php: function pot() { does something; returns a value; } In another page (page1.php), there is a link and a textbox: ...

What is the process for displaying an image based on a selection from a dropdown menu?

I am attempting to create a form that will show a movie poster once a user selects which movie they want to view. I have written a function for this purpose, but as a beginner in javascript, something seems to be going wrong. Any assistance you can provid ...