Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to setup so that the default namespace in root element in xml is also the assumed default namespace in the xpath #138

Open
ABDB619 opened this issue Dec 19, 2023 · 2 comments

Comments

@ABDB619
Copy link

ABDB619 commented Dec 19, 2023

Hello.

I have a similar use case to this example, where there is a default namespace:

var xpath = require("xpath")
var dom = require('@xmldom/xmldom').DOMParser;

var xml = "<book xmlns='http://example.com/book'><title>Harry Potter</title></book>"
var doc = new dom().parseFromString(xml, 'text/xml');
var select = xpath.useNamespaces({"bookml": "http://example.com/book"});
 
console.log(select('//bookml:title/text()', doc)[0].nodeValue);

But I would want to setup the select so that the default namespace is presumed in the xpath as well. Something like:

var xpath = require("xpath")
var dom = require('@xmldom/xmldom').DOMParser;

var xml = "<book xmlns='http://example.com/book'><title>Harry Potter</title></book>"
var doc = new dom().parseFromString(xml, 'text/xml');
var select = xpath.useNamespaces({"": "http://example.com/book"});
 
console.log(select('//title/text()', doc)[0].nodeValue);

But this doesn't seem to work. Is there a way to make this work?

@JLRishe
Copy link
Collaborator

JLRishe commented Dec 19, 2023

As explained here, there is no way to do what you're describing because it would not be compliant with the XPath 1.0 spec. There is no concept of a default namespace in XPath 1.0.

We make an exception for HTML nodes because there are HTML query engines that allow using XPath on HTML without a prefix even though they're technically in a namespace. But for other namespaces, you'll need to specify a prefix, which is the way XPath is designed to work.

@ABDB619
Copy link
Author

ABDB619 commented Jan 8, 2024

Ok, thanks for your response. Yeah, I did also found this article which also states that you just always have to use namespaces in xpath. Interesting is that this online evaluator seems to somehow get around that, probably by going "not compliant with xpath 1.0 spec" as you explained. Also this "feature" of the spec seems more like a bug as it means that without defining an alias for the default namespace, no xpath can ever hit anything from that namespace. Ok, so that keeping in mind, I decided to solve my problem by introducing a special namespace alias "default" which will be mapped to the default xmlns in the document if it is there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants