I use the function below, but not sure if it is always stable / safe ... Is this?
When and who is stable / safe for "reusing parts of DOMXpath preparation procedures"?
To simplify the use of the XPath query () method, we can use a function that remembers the last calls with static variables,
function DOMXpath_reuser($file) { static $doc=NULL; static $docName=''; static $xp=NULL; if (!$doc) $doc = new DOMDocument(); if ($file!=$docName) { $doc->loadHTMLFile($file); $xp = NULL; } if (!$xp) $xp = new DOMXpath($doc); return $xp;
This question is similar to this other about reusing XSLTProcessor. In both questions, the problem can be generalized to any language or structure that uses LibXML2 as its implementation of DomDocument.
There is another related question: How to update the "DOMDocument instances of LibXML2?"
Illustrating
Reuse is very useful (examples):
$f = "my_XML_file.xml"; $elements = DOMXpath_reuser($f)->query("//*[@id]"); // use elements to get information $elements = DOMXpath_reuser($f)->("/html/body/div[1]"); // use elements to get information
But if you do something like removeChild , replaceChild , etc. (example),
$div = DOMXpath_reuser($f)->query("/html/body/div[1]")->item(0); //STABLE $div->parentNode->removeChild($div); // CHANGES DOM $elements = DOMXpath_reuser($f)->query("//div[@id]"); // INSTABLE! !!
events may occur and requests will not work as expected !!
- When (which DOMDocument methods affect XPath?)
- Why can't we use something like normalizeDocument to "update the DOM" (exist?)?
- Only "new DOMXpath ($ doc)"; is it always safe? need to reload $ doc?
Peter Krauss
source share