Use the contextnode parameter to shorten our expression in PHP
Description
The following code shows how to use the contextnode parameter to shorten our expression.
Example
<?php//from w w w.j a v a 2 s . c o m
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->load('test.xml');
$xpath = new DOMXPath($doc);
$tbody = $doc->getElementsByTagName('tbody')->item(0);
// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';
$entries = $xpath->query($query, $tbody);
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>
The following code is for test.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [// w ww . ja va2 s.c o m
<!ELEMENT books (book+)>
<!ELEMENT book (title, author+, xhtml:blurb?)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT blurb (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ATTLIST books xmlns CDATA #IMPLIED>
<!ATTLIST books xmlns:xhtml CDATA #IMPLIED>
<!ATTLIST book id ID #IMPLIED>
<!ATTLIST author email CDATA #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://java2s.com/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<book id="php-basics">
<title>PHP Basics</title>
<author email="t@no.com">Tom</author>
<author email="j@no.com">Jack</author>
<xhtml:blurb>PHP Basics</xhtml:blurb>
</book>
<book id="php-advanced">
<title>PHP Programming</title>
<author email="j@no.php">Jack</author>
</book>
</books>