Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

Syntax:

Xpath namespace syntax is given as:

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:commentxmlns="http://www.w3.org/1999/xhtml">


Hello EDUCBA



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:

One page >Two page >Three page >

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













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



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

Output:

Example #2

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

Xpath Using PHP
hello.php
$xml =
My Shopping

Chapter 1
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..


Chapter 2
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..


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:

Example #3

$xml =

Depthi roy
Varma Singh

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:

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 itemNames = new ArrayList();
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 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




Kellogs choclate


L'Oreal Shampoo

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:

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

The post XPath namespace appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

XPath namespace

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×