Updated April 4, 2023
Definition of XPath attribute
For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document. When there are certain uniquely recognized attribute values accessible in the container tag, we employ the XPath functions (contains or starts-with) with the attribute. The “@” symbol is used to access attributes.
Syntax:
Xpath Syntax is given as:
Within a single node
/path to/element[@attribute_name]
At any point in the document
//*[@attribute_name]
Within a node that has some value
/path to/element[@attribute_name='search value']
/path to/element[@attribute_name="search value"]
Anywhere in the document that contains information of value
//*[@attribute_name='search string']
//*[@attribute_name="search string"]
How XPath attribute works?
Attribute predicates are another approach to indicate the items we want to choose more accurately. They are divided into two types: [@attr=”value”] chooses only elements with the attr attribute set to a value, and [@attr] selects only elements with an attr attribute set to a value (set to any value).
For example, let’s see an XML code like:
<purchase>
<product id=’soap’>
<name> Margo </name>
</purchase>
The Xpath goes like this:
/purchase/product[@id="soap"]/name
The following examples, which deal with qualities, are a little more complicated.
1. Choose objects that begin with the word “imagebox”:
//*
[starts-with(name(),'imagebox')]
2.Only objects from the “gallery” set should be selected:
/*[@sets=',gallery,']
3.Select the following objects from the set “gallery” that begins with the name albums:
/*[starts-with(name(),'albums')]
/*[@sets=',gallery,']
4.Choose between img_1 and img_ 2:
//img_1 | //img_2
5.Select all objects in the “blue” or “flower” sets:
//*[@sets,',blue,') or contains(@sets,'flower')]
6.Select all objects in the “blue” set but not the “flower” set:
//*[contains(@sets,',blue,') and not(contains(@sets,'flower')]
7.Select all items in sets that start with the letter “pot”:
//*[starts-with(@sets,',pot')]
Following Observations could be taken to see how attribute works with Xpath functions:
– If we know the partial constant visible text or attribute, utilise the “contains()” technique in XPath.
– If we know the starting partial constant visible text or attribute, utilise the “starts-with()” function in XPath.
– With absolute text or an attribute, we can also utilise the contains () and starts-with() methods.
Let’s take a real-time case:
The following is an example of an invalid case for the XPath function with the attribute:
When using the contains() and starts-with() methods, we need to be very careful about which attribute we utilize. We won’t be able to uniquely identify the element if the property value isn’t unique. The XPath won’t function if we use the “type” attribute to identify the “I’m Feeling Lucky” button.
The presence of two matching nodes indicates that the element has not been appropriately detected. The value of the type attribute is not unique in this case.
For instance
<Guardians name='Guardians'>
<Pa id='1' name='Pa_1'>
<tag name='tag'>
<chi name='kid_2' id='2'>kid2_Par_1</chi>
<chi name='kid__4' id='4'>kid4_Par_1</chi>
<chi name='kid__1' id='3'>kid1_Par_1</chi>
<chi name='kid__3' id='1'>kid3_Par_1</chi>
</tag>
</Pa>
<Pa id='2' name='Pa_2'>
<tag name='tag'>
<chi name='kid_5' id='2'>kid8_Par_1</chi>
<chi name='kid__4' id='4'>kid7_Par_1</chi>
<chi name='kid__1' id='3'>kid6_Par_1</chi>
<chi name='kid__7' id='1'>kid5_Par_1</chi>
</tag>
</Pa>
</Guardians>
The attribute expression is
//chi/@name
The result would be
<?xml version="1.0" encoding="UTF-8"?>
<result>
kid_2
kid__4
kid__1
kid__3
</result>
In the following section, we shall see how attribute works in java Programming to extract the specific element from the XML document rather than calling all the elements. Let’s get started:
Examples
Let us discuss examples of the XPath attribute.
Example #1: Using Simple Xpath Expression
state.xml
<?xml version="1.0" standalone="yes"?>
<stateinfo>
<client id="1">
<fullname> Kary Gate</fullname>
<position discipline="developer" service="3 year">Data Analyst</position>
<email>[email protected]</email>
</client>
<client id="12">
<fullname>John Das</fullname>
<position discipline="manger" service="10 year">Data Engineer</position>
<email>[email protected]</email>
</client>
<client id="21">
<fullname>David Frich</fullname>
<position discipline="Fresher" service="0 year">Programmer</position>
<email>[email protected]</email>
</client>
</stateinfo>
Xpath Expression
/stateinfo/client/@id
Output:
ii) Selecting all attribute value
Xpath Expression
//@*
This selects all attributes of the specified context node.
Output:
iii) Selecting discipline attribute
Xpath Expression
@discipline
Output:
Example #2
.xml
<Universe>
<uname>Milky Way</uname>
<Object uname="Mars" type="planet"/>
<Object uname="Star" type="galaxy"/>
</Universe>
Xpath Expression
/Universe/*[@uname]
Explanation
With Xpath expression let’s see how to extract the value of an attribute.
Output:
Finding Nodes with a Specific value on an attribute
/Universe/*[@uname='Star']
Output:
Find nodes by substring matching the value of an attribute.
Xpath Expression
/Universe/*[contains(@uname,'Ma')]
Output:
Find nodes using a substring that matches the beginning of an attribute’s value.
/Universe/*[starts-with(lower-case(@uname),'sta')]
Output:
Example #3: Using java
import java.util.ArrayList;
import java.util.List;
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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Attributepath
{
public static void main(String[] args) throws Exception
{
String fileName= "patient.xml";
Document doc = getDocument(fileName);
String xpathExpression = "";
xpathExpression = "/Patients/Patient/@id";
System.out.println( evaluateXPath(doc, xpathExpression) );
xpathExpression = "/Patients/Patient[Section/sname='neuro']/@id";
System.out.println( evaluateXPath(doc, xpathExpression) );
xpathExpression = "/Patients/Patient[firstName='Vivian']/@id";
System.out.println( evaluateXPath(doc, xpathExpression) );
xpathExpression = "/Patients/Patient/@id[. > 13]";
System.out.println( evaluateXPath(doc xpathExpression) );
xpathExpression = "/Patients/Patient[contains(@id,'11')]/firstName/text()";
System.out.println( evaluateXPath(doc, xpathExpression) );
xpathExpression = "descendant-or-self::*[contains(@id,'11')]/firstName/text()";
System.out.println( evaluateXPath(doc, xpathExpression) );
}
private static List<String> evaluateXPath(Document doc, String xpathExpression) throws Exception
{
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
List<String> values = new ArrayList<>();
try
{
XPathExpression expr = xp.compile(xpathExpression);
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int k= 0; k < nodes.getLength(); k++) {
values.add(nodes.item(k).getNodeValue());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return values;
}
private static Document getDocument(String fileName) throws Exception
{
DocumentBuilderFactory fa = DocumentBuilderFactory.newInstance();
fa.setNamespaceAware(true);
DocumentBuilder bu = fa.newDocumentBuilder();
Document d = bu.parse(fileName);
return d;
}
}
patient.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Patients>
<Patient id="11">
<firstName>Neeraj</firstName>
<lastName>Das</lastName>
<Section>
<sid>101</sid>
<sname>Cardio</sname>
<disease> heart</disease>
</Section>
</Patient>
<Patient id="12">
<firstName>Gokul</firstName>
<lastName>Karthik</lastName>
<Section>
<sid>102</sid>
<sname>neuro</sname>
<disease> brain</disease>
</Section>
</Patient>
<Patient id="13">
<firstName>Vivian</firstName>
<lastName>togi</lastName>
<Section>
<sid>103</sid>
<sname>xxxk</sname>
<disease> Kidney</disease>
</Section>
</Patient>
<Patient id="14">
<firstName>Smitha</firstName>
<lastName>vivek</lastName>
<Section>
<sid>104</sid>
<sname>Scan</sname>
<disease> Thyroid</disease>
</Section>
</Patient>
<Patient id="15">
<firstName>Swathi</firstName>
<lastName>Prasana</lastName>
<Section>
<sid>105</sid>
<sname>artho</sname>
<disease> haemo</disease>
</Section>
</Patient>
.</Patients>
Explanation
The above code loads the XML from.xml into a DOMDocument object instance. It then utilizes the includes a method to find all attributes that contain the element in an XPath query.
Output:
Conclusion
Therefore, this article offers a code example that shows how to implement this requirement by using the contains XML Path Language (XPath) Attribute function. In the following post, we’ll look at how to use XPath Functions to improve the position of elements on the available webpage.
Recommended Articles
This is a guide to XPath attribute. Here we discuss the definition, How XPath attribute works? And examples for better understanding. You may also have a look at the following articles to learn more –