|
Server : Apache/2.4.62 System : FreeBSD fbsdweb2.web.rcn.net 14.1-RELEASE FreeBSD 14.1-RELEASE releng/14.1-n267679-10e31f0946d8 GENERIC amd64 User : www ( 80) PHP Version : 8.3.8 Disable Function : NONE Directory : /domains/simes/unused/fCMSBackend/includes/xpath/ |
Upload File : |
<?php
Class FCMSXPath {
var $dom;
var $xp;
# ----- Std. functions
function parse ($s, $fromFile = True) {
$this->dom = new DOMDocument;
//$this->preserveWhiteSpace = false;
if ($fromFile) {
$ret = $this->dom->load ($s);
}
else {
$ret = $this->dom->loadXML ($s);
}
if ($ret) $this->xp = new DOMXPath ($this->dom);
else $this->xp = NULL;
return $ret;
}
function match ($xpath) {
$ret = $this->xp->query ($xpath);
return $ret;
}
function matchNode ($xpath) {
$n = $this->match ($xpath);
if (! $n) return $n;
$ret = $n->item (0);
return $ret;
}
// Just like match, but returns elment names.
function matchNames ($xpath) {
$ret = array ();
$rs = $this->match ($xpath);
foreach ($rs as $node) {
$name = $this->getNodeName ($node);
array_push ($ret, $name);
}
return $ret;
}
# ----- Node functions
# They take either xpath or node object.
function getNodeName ($n) {
if (gettype ($n) == "string") $n = $this->matchNode ($n);
if (! $n) return "";
return $n->nodeName;
}
function getNodeValue ($n) {
if (gettype ($n) == "string") $n = $this->matchNode ($n);
if (! $n) return "";
$ret = '';
foreach ($n->childNodes as $child) {
if ($child->nodeType == XML_TEXT_NODE) {
$ret .= $child->data;
}
}
return $ret;
}
function getAttribute ($node, $attr) {
if (gettype ($node) == "string") $node = $this->matchNode ($node);
if (! $node) return "";
return $node->getAttribute ($attr);
}
# ----- Export
// Accepts either node or xpath.
function exportNodeAsXML ($n) {
if (gettype ($n) == "string") $n = $this->matchNode ($n);
if (! $n) return "";
$ret = $this->dom->saveXML ($n);
return $ret;
}
function exportTreeAsXML () {
$ret = $this->dom->saveXML ();
return $ret;
}
function exportToFile ($file) {
return $this->dom->save ($file);
}
# ----- Tree modification
function createSingleChildNodeOf ($parent_xpath, $element) {
$p = $this->matchNode ($parent_xpath);
foreach ($p->childNodes as $c) {
if ($c->nodeName == $element) return;
}
$newn = $this->dom->createElement ($element);
$ret = $p->appendChild ($newn);
return $ret;
}
function appendChildNodeOf ($parent_xpath, $element) {
$p = $this->matchNode ($parent_xpath);
$newn = $this->dom->createElement ($element);
$ret = $p->appendChild ($newn);
return $ret;
}
function setAttribute ($node, $attr, $var) {
if (gettype ($node) == "string") $node = $this->matchNode ($node);
$node->setAttribute ($attr, $var);
}
function setNodeValue ($node, $value) {
if (gettype ($node) == "string") $node = $this->matchNode ($node);
$clist = $node->childNodes;
foreach ($clist as $child) {
if ($child->nodeType == XML_TEXT_NODE) {
$node->removeChild ($child);
}
}
$newn = $this->dom->createTextNode ($value);
$node->appendChild ($newn);
}
}
?>