XPath technology
XPathTechnology
##Basic Overview
is the XML path language, which is a path language used to determine XML (subset of Standard Universal Markup Language) The language of a portion of a document. XPathThe tree structure based on XML provides the ability to find nodes in the data structure tree. The original intention of XPath was to use it as a universal interface between XPointer and XSLT# Grammar model between ##. But XPath was quickly adopted by developers as a small query language.
PS: It cooperates with DOM4J parsing technology to make up for DOM4J The disadvantage of not being able to get elements across layers. The jaxen-1.1-beta-6.jar package needs to be introduced.
XPath
PrincipleXPath
is likeSQLQuery statement can query the DOM tree and obtain the corresponding results.
XPath
CaseXML9.xml
<?xml version="1.0" encoding="utf-8"?>
<AAA>
<BBB id="b1">Hello World B1</BBB>
<CCC id="c1"/>
<BBB id="b2">Hello World B2</BBB>
<BBB>Hello World B3</BBB>
<DDD>
<BBB id="b3">Hello World B4</BBB>
</DDD>
<CCC>
<DDD>
<BBB id="b4"/>
<BBB id="b5"/>
</DDD>
</CCC>
</AAA>
package com.pc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
* @author Switch
* @function DOM4j配合xpath
*
*/
public class XML9 {
public static void main(String[] args) throws Exception {
// 1.得到SAXReader解析器
SAXReader saxReader = new SAXReader();
// 2.指定解析哪个文件
Document document = saxReader.read("src/com/pc/XML9.xml");
// 3.使用XPath随意读取任何一层的元素
// document.selectNodes(); //返回多个元素
// document.selectSingleNode(); // 返回一个元素
// 取出AAA下面的所有BBB 3个
// List nodeList = document.selectNodes("/AAA/BBB");
// 取出所有的BBB 6个
// List nodeList = document.selectNodes("//BBB");
// System.out.println(nodeList.size());
// 取出AAA下面的DDD下面的最后一个BBB元素的内容 Hello World B4
// List nodeList = document.selectNodes("/AAA/DDD//BBB[last()]");
// System.out.println(((Element)nodeList.get(0)).getTextTrim());
// 取出AAA下面的CCC下面的DDD下面的所有元素 2个
// List nodeList = document.selectNodes("/AAA/CCC/DDD/*");
// 取出所有有三个祖先元素的BBB元素
// List nodeList = document.selectNodes("/*/*/*/BBB");
// System.out.println(nodeList.size());
// 取出AAA下面的第一个BBB元素的内容 Hello World B1
// List nodeList = document.selectNodes("/AAA/BBB[1]");
// System.out.println(((Element)nodeList.get(0)).getTextTrim());
// Element element = (Element) document.selectSingleNode("/AAA/BBB[1]");
// System.out.println(element.getTextTrim());
// 取出所有有id属性的元素的id属性 5个
// List nodeList = document.selectNodes("//@id");
// System.out.println(nodeList.size());
// 取出第一个有id属性的元素的id属性的值 b1
// System.out.println(((Attribute)nodeList.get(0)).getText());
// 取出所有有id属性的CCC元素
// List nodeList = document.selectNodes("//CCC[@id]");
// System.out.println(nodeList.size());
// "//BBB[@*]" 选择有任意属性的BBB元素
// "//BBB[not(@*)]" 选择没有属性的BBB元素
// "//BBB[@id='b1']" 选择含有属性id且其值为'b1'的BBB元素
// 选择含有属性id且其值(在用normalize-space函数去掉前后空格后)为'b2'的BBB元素
// "//BBB[normalize-space(@id)='b2']"
// "//*[count(BBB)=2]" 选择含有2个BBB子元素的元素
// "//*[name()='BBB']" 选择所有名称为BBB的元素(这里等价于//BBB)
// "//*[starts-with(name(),'B')]" 选择所有名称以"B"起始的元素
// "//*[contains(name(),'C')]" 选择所有名称包含"C"的元素
// "//*[string-length(name()) = 3]" 选择名字长度为3的元素
// "//*[string-length(name()) < 4]" 选择名字长度小于3的元素
// 同样的将<替换成大于号则是大于
// 11个
// List nodeList = document.selectNodes("//*[string-length(name()) < 4]");
// System.out.println(nodeList.size());
// "//CCC | //BBB" 选择所有的CCC和BBB元素
}
}: Through the XPath statement in the above case, the basic XML query, there is no problem in using it.
The above is the content of XPath technology. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20519
7
13632
4
How to format and beautify XML code in Notepad ? (Pretty Print)
Mar 07, 2026 am 12:20 AM
Notepad needs to manually install and enable the XMLTools plug-in to format XML; if the tags are messed up or the content is lost after formatting, it means that the XML itself is illegal, and there are problems such as unclosed tags or illegal characters.
How to convert XML to YAML for DevOps? (Configuration Management)
Mar 12, 2026 am 12:11 AM
xmltodict PyYAMListhesafestcomboforDevOpsconfigfilesbecauseitpreservescomments,CDATA,namespaces,andattributesaccurately,unlikerawXML-to-YAMLtoolsorCLIutilitieslikeyqandxmllintwhichsilentlydropcriticalmetadata.
How to minify XML files for faster web loading? (Performance Optimization)
Mar 08, 2026 am 12:16 AM
RunningminifyonXMLwithoutunderstandingitsrulesbreaksparsingoralterssemanticsbecausewhitespacecanbemeaningful;safeminificationrequiresdata-orientedXML,controlledgeneration/consumption,andstrictparserawareness.
How to convert an XML file to a Word document? (Reporting)
Mar 09, 2026 am 01:05 AM
python-docx does not support direct reading of XML files. You need to use xml.etree.ElementTree or lxml to parse the XML extraction fields first, and then write them into the Document object segment by segment. Explicit declaration of prefixes is required to process namespaces, and manual manipulation of the underlying XML is required for table merging and styling. Chinese paths should be avoided when saving.
How to parse XML data from a URL API? (Rest Services)
Mar 13, 2026 am 12:06 AM
To parse remote XML API in Python, you need to use requests to get the response and then check the status code and Content-Type. Prioritize using r.text with xml.etree.ElementTree to parse; when encountering a namespace, you need to pass the namespace dictionary; use iterparse to stream large files and clear them manually; front-end JS requires CORS support or proxy.
How to use Attributes vs Elements in XML? (Design Best Practices)
Mar 16, 2026 am 12:26 AM
You should use attributes to store short metadata (such as id, type), and use elements to store scalable content data; because attributes do not support namespaces, duplication, nesting, and internationalization, their parsing is error-prone and maintenance is difficult.
How to open and view XML files in Windows 11? (Beginner Guide)
Mar 12, 2026 am 01:02 AM
The XML file cannot be opened by double-clicking because it is associated with Notepad by default, causing confusion in the display. You should use Notepad, VSCode or Edge instead; Edge can format and report errors, while VSCode requires the installation of extensions such as RedHatXML for normal highlighting, indentation and verification.
How to read XML data in C# using LINQ? (.NET Development)
Mar 15, 2026 am 12:43 AM
XDocument.Load() is the preferred method for reading local XML files and automatically handles encoding, BOM and format exceptions; absolute or correct relative paths are required; namespaces must be explicitly declared and participate in queries; Elements() and Descendants() behave differently and should be selected as needed; string parsing must capture XmlException and verify the source.





