?php// 详细学习可以参考w3" /> ?php// 详细学习可以参考w3">
Home Database Mysql Tutorial XPath快速解析XML

XPath快速解析XML

Jun 07, 2016 pm 04:10 PM
xml xpath one Why use fast parse

为什么要使用XPATH,上一篇博客查询越靠近下面单词,时间会越长,超过2s就不太好了,XPAth就是用来提高解析XML速度的。还可以解析html,效率也是不错的! 分别查询下列信息 代码: vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:sql;">?php// 详细学习可以参考w3

为什么要使用XPATH,上一篇博客查询越靠近下面单词,时间会越长,超过2s就不太好了,XPAth就是用来提高解析XML速度的。还可以解析html,效率也是不错的!

分别查询下列信息

\

代码:喎?http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:sql;">load('book.xml'); $xpath = new DOMXPATH($xml); /* $sql = 'xxx'; // 路径表达式 $xpath->query($sql); */ /* xpath的路径表达式如何写? xpath是从根节点到某个节点声经过的路径 */ // 查询book.xml下面的每本书的title // /bookstore/book/title /* $sql = '/bookstore/book/title'; $rs = $xpath->query($sql); print_r($rs); echo $rs->item(1)->nodeValue; */ // 查询book.xml下面book节点的下面的第2个title节点,哪来的第2个title节点? 这样写是不对的 /* $sql = '/bookstore/book/title[2]'; $rs = $xpath->query($sql); print_r($rs->length); */ // 查询bookestore下面的第2本书下面的title节点. /* $sql = '/bookstore/book[2]/title'; $rs = $xpath->query($sql); print_r($rs->item(0)->nodeValue); */ // 查询bookstore下面的book节点并且价格>40元 /* $sql = '/bookstore/book[price>40]/title'; $rs = $xpath->query($sql); echo $rs->item(0)->nodeValue; */ // 查询侠客行的价格 // /bookstore/下面的book,且title=='侠客行'的书的价格 $sql = '/bookstore/book[title="侠客行"]/price'; $rs = $xpath->query($sql); echo $rs->item(0)->nodeValue;
xpath如何不考虑路径的层次,来查询某个节点


比如我们刚才严格层次查询 /bookstore/book/title
现在我们加了一个,

<?php
$xml = new DOMDocument(&#39;1.0&#39;,&#39;utf-8&#39;);
$xml->load(&#39;book.xml&#39;);

$xpath = new DOMXPATH($xml);

$sql = &#39;/bookstore/book[last()]/title&#39;;
$rs = $xpath->query($sql);

// 只能查到书名的title
//echo $rs->item(0)->nodeValue; 


// 思考 ,如何查询所有的title,不考虑层次关系?
$sql = &#39;/title&#39;; // 这样不行,这样查的是根节点下的title,而根节点下没有title

/*
/a/b,这说明,a,b就是父子关系,而如果用/a//b,这样说明a只是b的祖先就行,忽略了层次
*/


// 不分层次,查出所有的title
/*
$sql = &#39;//title&#39;;
foreach($xpath->query($sql) as $v) {
    echo $v->nodeValue,&#39;<br />&#39;;
}
*/

/*
$sql = &#39;//title[2]&#39;; // 这样又理解成<title>a</title><title>b</title>,查询所有相邻的title节点,且第2个
foreach($xpath->query($sql) as $v) {
    echo $v->nodeValue,&#39;<br />&#39;;
}
*/
Copy after login

上面是简单应用,来改善上篇博客效率问题

<?php
// 接收单词并解析XML查询相应的单词
$word = isset($_GET[&#39;word&#39;])?trim($_GET[&#39;word&#39;]):&#39;&#39;;

if(empty($word)) {
    exit(&#39;你想查啥?&#39;);
}


// 解析XML并查询
$xml = new DOMDocument(&#39;1.0&#39;,&#39;utf-8&#39;);
$xml->load(&#39;./dict.xml&#39;);


/*
$namelist = $xml->getElementsByTagName(&#39;name&#39;);

$isfind = false;

foreach($namelist as $v) {
    if($v->nodeValue == $word) {
        //print_r($v);
        echo $word,&#39;<br />&#39;;
        echo &#39;意思:&#39;,$v->nextSibling->nodeValue,&#39;<br />&#39;;
        echo &#39;例句:&#39;,$v->nextSibling->nextSibling->nodeValue,&#39;<br />&#39;;

        $isfind = true;
        break;
    }
}

if(!$isfind) {
    echo &#39;sorry&#39;;
}
*/






// 接下来用xpath来查询词典
$xpath = new DOMXpath($xml);

// 查询/dict下的word,且name=$word的节点下面的/name节点
$sql = &#39;/dict/word[name="&#39; . $word . &#39;"]/name&#39;; 
//echo $sql;
$words = $xpath->query($sql);

if($words->length == 0) {
    echo &#39;sorry&#39;;
    exit;
}


// 查到了
$name = $words->item(0);
echo $word,&#39;<br />&#39;;
echo &#39;意思:&#39;,$name->nextSibling->nodeValue,&#39;<br />&#39;;
echo &#39;例句:&#39;,$name->nextSibling->nextSibling->nodeValue,&#39;<br />&#39;;
Copy after login

来解析一下的html

<?php
/***
====笔记部分====
xpath是根据DOM标准来查询,
html也是DOM,
也能查,岂只是xml
***/


$html = new DOMDocument(&#39;1.0&#39;,&#39;utf-8&#39;);
$html->loadhtmlfile(&#39;dict.html&#39;);


$xpath = new DOMXPATH($html);
$sql = &#39;/html/body/h2&#39;;
echo $xpath->query($sql)->item(0)->nodeValue,&#39;<br />&#39;;


// 查询id="abc"的div节点
$sql = &#39;//div[@id="abc"]&#39;;
echo $xpath->query($sql)->item(0)->nodeValue;


// 分析第2个/div/下的p下的相邻span的第2个span的内容
$sql = &#39;//div/p/span[2]&#39;;
echo $xpath->query($sql)->item(0)->nodeValue;
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos stops maintenance 2024 Centos stops maintenance 2024 Apr 14, 2025 pm 08:39 PM

CentOS will be shut down in 2024 because its upstream distribution, RHEL 8, has been shut down. This shutdown will affect the CentOS 8 system, preventing it from continuing to receive updates. Users should plan for migration, and recommended options include CentOS Stream, AlmaLinux, and Rocky Linux to keep the system safe and stable.

What are the tools to connect to mongodb What are the tools to connect to mongodb Apr 12, 2025 am 06:51 AM

The main tools for connecting to MongoDB are: 1. MongoDB Shell, suitable for quickly viewing data and performing simple operations; 2. Programming language drivers (such as PyMongo, MongoDB Java Driver, MongoDB Node.js Driver), suitable for application development, but you need to master the usage methods; 3. GUI tools (such as Robo 3T, Compass) provide a graphical interface for beginners and quick data viewing. When selecting tools, you need to consider application scenarios and technology stacks, and pay attention to connection string configuration, permission management and performance optimization, such as using connection pools and indexes.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Why does the Spring project cause randomness problems due to circular dependencies when starting? Why does the Spring project cause randomness problems due to circular dependencies when starting? Apr 19, 2025 pm 11:21 PM

Understand the randomness of circular dependencies in Spring project startup. When developing Spring project, you may encounter randomness caused by circular dependencies at project startup...

Can vscode be used in python Can vscode be used in python Apr 15, 2025 pm 08:30 PM

Can VS Code be competent for Python development? Absolutely! It is lightweight and flexible, and can provide most of the features of PyCharm by installing extensions. Key extensions include Python extension packages (basics), code formatting tools (readability), linter (Error checking), and debugging tools. The Python extension package gives VS Code Python development capabilities, including code highlighting, smart prompts and debugging. Advanced tips include powerful debugging capabilities and performance optimization tools. Frequently asked questions such as environment configuration and code formatting can be solved through virtual environments and formatting tools. Make good use of the expansion ecosystem and make careful choices. VS Code will become a powerful tool for Python development.

See all articles