Clément
Clément

Reputation: 729

Is it possible to specify the namespace prefix just once in a xpath expression?

I have only one namespace in my XML file, defined on the root element.

<root xmlns="http://my-namespace">
    <aChild>
        <secondChild />
    ...

Is it possible to avoid writing it before each element of my xpath expression ?
After doing

xmlNamespaceManager.AddNamespace("ns", "http://my-namespace");

I have to write

xml.SelectNodes("ns:root/ns:aChild/ns:secondChild", xmlNamespaceManager);

And it would be much easier to do just

xml.SelectNodes("ns:root/aChild/secondChild", xmlNamespaceManager);

I have developpers who send xpath expressions to the XML but they don't necessarily know the prefix or the namespace, they just know they have to access root/aChild/secondChild.

Thank you.

Upvotes: 1

Views: 837

Answers (2)

mdma
mdma

Reputation: 57777

Unfortunately as intuitive as it seems, there's no easy way do define the default namespace in XPath. An XPath name without a namespace declaration binds to the null namespace, rather than the URI assigned to the default namespace.

This is discussed in XPath default namespace handling and Easy things should be Easy

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

you can add the namespace at document level

  XmlDocument doc = new XmlDocument();  

  XmlSchema schema = new XmlSchema();
  schema.Namespaces.Add("xmlns", "http://www.sample.com/file");

  doc.Schemas.Add(schema);

Upvotes: 1

Related Questions