secret
Created

Using DOMXml and Xpath, to update XML entries

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
<?php
/**
* http://stackoverflow.com/questions/9671273/using-domxml-and-xpath-to-update-xml-entries
*/
 
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<storagehouse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="schema.xsd">
<item id="c7278e33ef0f4aff88da10dfeeaaae7a">
<name>HDMI Cable 3m</name>
<weight>0.5</weight>
<category>Cables</category>
<location>B3</location>
</item>
<item id="df799fb47bc1e13f3e1c8b04ebd16a96">
<name>Dell U2410</name>
<weight>2.5</weight>
<category>Monitors</category>
<location>C2</location>
</item>
</storagehouse>
XML;
 
class ItemNode
{
private $node;
private $createData;
 
public function __construct(DOMNode $node)
{
$this->node = $node;
$this->snapshot();
}
 
/**
* did the repository node changed since last snapshot?
*
* @return bool
*/
public function hasChanged() {
return !$this->arraysAreEqual($this->getData(), $this->createData);
}
 
/**
* compare arrays for equality but w/o key order
* @param array $a
* @param array $b
* @return bool
*/
private function arraysAreEqual(array $a, array $b)
{
if (count($a) != count($b)) {
return FALSE;
}
foreach($a as $name => $value)
{
if (!array_key_exists($name, $b)) return FALSE;
if ($b[$name] !== $a[$name]) return FALSE;
}
return TRUE;
}
 
public function itemHasChanges(Item $item)
{
return !$this->arraysAreEqual(get_object_vars($item), $this->createData);
}
 
public function snapshot()
{
$this->createData = $this->getData();
}
 
public function overloadObject($object)
{
foreach ($this->getData() as $name => $value) {
$object->$name = $value;
}
}
 
/**
* @return array
*/
public function getData()
{
$values = array();
foreach ($this->node->childNodes as $child) {
/* @var $child DOMElement */
if ($child instanceof DOMElement) {
$values[$child->localName] = $child->nodeValue;
}
}
return $values;
}
 
public function updateWith(Item $item)
{
$data = get_object_vars($item);
$this->setData($data);
$this->snapshot();
}
 
public function setData(array $data)
{
foreach ($data as $name => $value)
{
$this->setValue($name, $value);
}
}
 
private function setValue($name, $value)
{
$xp = new DOMXPath($this->node->ownerDocument);
$result = $xp->query(sprintf('./%s', $name), $this->node);
if (!$result || $result->length != 1) {
throw new InvalidArgumentException(sprintf('Value "%s" does not exist.', $name));
}
$result->item(0)->nodeValue = $value;
}
}
 
class Repository
{
private $doc;
private $provided = array();
 
public function __construct($xml)
{
$doc = new DOMDocument();
$doc->loadXML($xml);
$this->doc = $doc;
}
 
public function getItemByID($id)
{
$xp = new DOMXPath($this->doc);
if (($result = $xp->query(sprintf('//item[@id="%s"]', $id))) && $result->length == 1) {
$node = new ItemNode($result->item(0));
$item = new Item($id);
$node->overloadObject($item);
$this->register($item, $node);
return $item;
} else {
throw new InvalidArgumentException(sprintf('No Item with id "%s" exists.', $id));
}
}
 
private function register($object, ItemNode $node)
{
$this->provided[] = array($object, $node);
}
 
public function saveChanges()
{
$updates = array();
foreach($this->provided as $entity)
{
/* @var $object Item */
/* @var $node ItemNode */
list($object, $node) = $entity;
if ($node->hasChanged()) {
throw new UnexpectedValueException('Transaction not safe (DOMElement Node has changed).');
}
if ($node->itemHasChanges($object)) {
$changes[] = $entity;
}
}
if (!count($changes)) {
return;
}
 
foreach($changes as $entity) {
list($object, $node) = $entity;
$node->updateWith($object);
}
}
 
public function getXML() {
return $this->doc->saveXML();
}
}
 
class Item
{
private $id;
 
public function __construct($id)
{
$this->id = $id;
}
 
public function getID()
{
return $this->id;
}
}
 
$id = "df799fb47bc1e13f3e1c8b04ebd16a96";
 
$simplexml = simplexml_load_string($xml);
$result = $simplexml->xpath(sprintf('/storagehouse/item[@id="%s"]', $id));
if (!$result || count($result) !== 1) {
throw new Exception(sprintf('Item with id "%s" does not exists or is not unique.', $id));
}
list($item) = $result;
$item->category = 'LCD Monitor';
echo $simplexml->asXML();
 
 
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$result = $xpath->query(sprintf('/storagehouse/item[@id="%s"]', $id));
if (!$result || $result->length !== 1) {
throw new Exception(sprintf('Item with id "%s" does not exists or is not unique.', $id));
}
$item = $result->item(0);
$category = $xpath->query('./category', $item)->item(0);
$category->nodeValue = "LCD Monitor";
echo $doc->saveXML($item);
 
 
$repository = new Repository($xml);
$item = $repository->getItemByID($id);
$item->category = 'LCD Monitor';
$repository->saveChanges();
echo $repository->getXML();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.