EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials XML Tutorial XPath namespace
 

XPath namespace

Updated March 29, 2023

XPath namespace

 

 

Introduction to XPath namespace

In an XML document, namespaces are used to provide uniquely named components and attributes. A namespace is made up of two parts: a prefix and a URL. This indicates the location of a document that defines the namespace in question. Name matching is preferred on a local name and a namespace prefix alone. The Namespaces helper class, introduced in version 1.3, makes it simple to use namespaces with XPath expressions.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax:

Xpath namespace syntax is given as:

<element xmlns:name = "URL">

A set of reserved attributes is used to declare a namespace. The name of such an attribute must be xmlns or include xmlns: as a prefix. These properties, like all others in XML, can be specified explicitly or by default.

How does XPath namespace work?

Namespaces are likely the most inconvenient aspect of using XPath. Consider the XML below to learn why. With the inclusion of a default namespace, it looks quite similar to the example at the top of this post. There is no method to connect a namespace prefix to a namespace in XPath. The hosting library can provide these services. It is strongly advised that we take advantage of those features and create namespace prefixes that may be used to qualify XML element and attribute names as needed. Within XML nodes and elements, the prefix is simply a reference to the namespace URL. As a result, several prefixes can be bound to the same namespace, and these prefixes can be mixed in a document. As a result, because all prefixes point to the same URL, all elements will be in the same namespace.

In various documents, the same prefix may be assigned to a different namespace.

Namespaces:

  • Namespaces can be set to their default values.
  • Only element names without prefixes are affected.

Example:

<a:Xpathdemo xmlns:a="urn:varid:ISBN+sampledoc.org:Xpathdemo:en">
<a:comment xmlns="http://www.w3.org/1999/xhtml">
<p>
Hello EDUCBA
</p>
</a:comment>
</Xpathdemo>

Undeclaring namespace

Xmlns=""

Xpath name and namespaces include:

  • A QName can be used in any step expression: h: body
  • External to the expression, the prefix binding is defined (e.g. application-specific).
  • The local name and namespace name, not the prefix, are used to match.
  • To the below examples, we could add namespaces:
<book><page>One</page><page>Two</page><page>Three</page></book>

The namspaces are added with the prefix ‘m’ ‘n’ and ‘k’

/m:book/n:page/m:book/n:page/k:a/@href

Predicates that test against local-name() can be written as an alternative:

*[local-name()='']/*[local-name(send)='QueryResponse']

Here, we introduce a namespace and demonstrate how to modify an XPath expression to account for it.

Xpath using Multiple Namespaces

<x xmlns="uri1" xmlns:new2="uri2">
<y xmlns:new3="uri3">
<new3:m>
<text></text>
<hello></hello>
<here></here>
</new3:m>
<new3:n xmlns="uri4">
<buy></buy>
<and></and>
<sell></sell>
</new3:n>
</y>
</x>

We have used multiple namespaces with different prefixes. The following XPath successfully navigated to the node:

/def:x/def:y/new3:n/def2: buy

Namespace awareness is built into XPath, and node tests match both local name and namespace. The evaluator assumes the node does not have a namespace if we don’t specify one in the path.

Example

Here we discuss the examples mentioned below.

Example #1

<?xml version="1.0" encoding="UTF-8"?>
<my:base xmlns:my="http://www.educba.com/mynamespace">
<my:dervived1 my:name="pravi">
<my:dervived2 my:name="prathiba">
<my:dervived3 my:name="Divya" />
</my:dervived2>
</my:dervived1>
</my:base>

XPath expression

/*["base"=local-name()]

Output:

XPath namespace output 1

Example #2

In an XPath query, you can specify a namespace prefix.

Xpath Using PHP

hello.php

<?php
$xml = <<<EOD
<shop xmlns:prod="http://example.org/prod-name">
<name>My Shopping</name>
<product id="1">
<prod:name>Chapter 1</prod:name>
<para>Lakme products can do to highlight and contour my naturally beautiful face. The colors match my complexion and we never look like having on a mask or caked up powder on my face..</para>
</product>
<product id="2">
<prod:name>Chapter 2</prod:name>
<para>Mac products can do to highlight and contour my naturally beautiful face. The colors match my complexion and we never look like  having on a mask or caked up powder on my face..</para>
</product>
</shop>
EOD;
$sxe = new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('c', 'http://educba.org/product-name');
$result = $sxe->xpath('//c:name');
foreach ($result as $name) {
echo $name . "\n";
}
?>

Explanation

The sample XML document creates a namespace with the prefix prod. Consider the possibility that this document previously used a c prefix for the same namespace. The XPath query will no longer provide the correct results as a result of the change, and the query will need to be modified. Even if the provider changes the namespace policy, using registerXPathNamespace prevents future changes to the query.

Output:

XPath namespace output 2

Example #3

<?php
$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<flights xmlns:f="http://educba.org/ns" xmlns:d="http://educba.org/demo">
<f:passenger id="1">Depthi roy</f:passenger>
<f:passenger id="2">Varma Singh</f:passenger>
</flights>
XML;
$sxe = new SimpleXMLElement($xml);
$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

Explanation

The above code returns a namespace in the document. It returns all the namespaces in the XML document used in parent and child nodes. The method getNamespaces returns an array of namespaces specified with their URIs.

Output:

output 3

Example #4

newdemo.java

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class newdemo
{
public static void main(String[] args) throws Exception
{        ArrayList<String> itemNames = new ArrayList<String>();
DocumentBuilderFactory fa = DocumentBuilderFactory.newInstance();
fa.setNamespaceAware(true);
DocumentBuilder bu= fa.newDocumentBuilder();
Document dmt = bu.parse(new FileInputStream(new File("department.xml")));
XPathFactory xpf= XPathFactory.newInstance();
XPath xp = xpf.newXPath();
xp.setNamespaceContext(new NamespaceResolver(dmt));
XPathExpression ex = xp.compile("//bs:departmentStore/bs:item/bs:itemname/text()");
Object result = ex.evaluate(dmt, XPathConstants.NODESET);
NodeList nd = (NodeList) result;
for (int k = 0; k < nd.getLength(); k++) {
itemNames.add(nd.item(k).getNodeValue());
}
System.out.println(itemNames);
}
}
class NamespaceResolver implements NamespaceContext
{
private Document sd;
public NamespaceResolver(Document dmt) {
sd = dmt;
}
public String getNamespaceURI(String prefix) {
if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
return sd.lookupNamespaceURI(null);
} else {
return sd.lookupNamespaceURI(prefix);
}
}
public String getPrefix(String namespaceURI) {
return sd.lookupPrefix(namespaceURI);
}
@SuppressWarnings("rawtypes")
public Iterator getPrefixes(String namespaceURI) {
return null;
}
}

department.xml

<?xml version="1.0" encoding="UTF-8"?>
<bs:departmentStore xmlns:bs="http://departmentstore.com/schemes">
<bs:item id="1">
<bs:itemname>Kellogs choclate</bs:itemname>
</bs:item>
<bs:item id="2">
<bs:itemname>L'Oreal Shampoo</bs:itemname>
</bs:item>
</bs:departmentStore>

Explanation

In the above java example, we have seen Path namespace resolution into an XML file department.xml using Namespace Context which has namespace declarations and respective usages. This namespace resolver works with any XML file that has namespace definitions. It scans the XML document for namespace declarations for any specific namespace prefix – passed as a parameter. As a result, there is no need to construct a separate namespace mapping. And the output of the above source code by extracting a text is shown below.

Output:

output 4

Conclusion

Therefore, in this article, we have seen how to use namespaces in an Xpath using java and Php with an example. Not surprisingly, the XML library provides methods to implement this.

Recommended Articles

This is a guide to XPath namespace. Here we discuss how to use namespaces in an Xpath using java and Php with an example. You may also have a look at the following articles to learn more –

  1. XPath Descendant
  2. XPath Relative
  3. XPath parent
  4. XPath Axes

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Limited Time Offer! - ENROLL NOW