1. Getting Started
XPath is the XML Path Language. It is a Language used to determine a part of the XML document.
The XML-based tree structure of XPath provides the ability to search nodes in the data structure tree. At first, the original intention of XPath was to use it as a general,
A syntax model between XPointer and XSL. However, XPath is quickly adopted by developers as a small query language.
2. Learn more
If you want to locate a node in the xml document and obtain the relevant information. You can search all nodes in the dom tree. This is obviously troublesome.
Therefore, it is easier to access the node of the tree with the XPat language.
For example:
.....
JIMI
male
.....
Perform the following operations:
1. Get the document node.
2. enumerate its child elements.
3. Locate the user element.
4. Obtain the first element of the user element, that is, the name element.
5. Obtain the first element of the name element, that is, the content in the name tag. (Text node)
6. Obtain the data of the Text node.
XPath can be used to describe a group of nodes in an XML document. For example:
/Gridbag/row
Indicates all row elements in the child element of the root element gridbag. You can use the [] operator to select a specific element.
/Gridbag/row [1]
Indicates the first element of all elements of the row.
You can use the @ operator to obtain the attributes of an element. ( : The id is the property of the user element)
/Gridbag/row [1]/cell [1]/@ author
The above XPath describes the author element of the first cell in the first row.
XPath expression:/gridbag/row/cell/@ author
Describes the author attribute nodes of all cells in the row element of the child element that acts as the root element gridbag.
3. XPath in java
Java uses XPath objects to operate xml documents
XPathFactory xpfactory = XPathFactory. newInstance ();
XPath path = xpfactory. newXPath ();
String name = path. evaluate ("/config/user/name", (Document) doc); // obtain the corresponding name by calculating the expression
Perform the following operations:
Nodelist nodes = (Nodelist) path. evaluate ("/gridbag/row", doc, XPathContants. NODESET); // a group of nodes are returned.
Node node = (Node) path. evaluate ("/gridbag/row [1]", doc, XPathContants. NODE); // return a Node.
Int count = (Number) path. evaluate ("count (/gridbag/row)", doc, XPathContants. NUMBER). intValue (); // return the Number of nodes.
If you want to compute a node from a node or node column, you can use:
Reusult = path. evaluate (expression, node.
-------------------------------------- The creation process of the doc variable is as follows. -------------
DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance ();
DocumentBuilder builder = factory. newDocumentBuilder ();
File f = new File ();
Document doc = builder. parse (f );