Home >Backend Development >PHP Tutorial >请问一个XML有关问题
请教一个XML问题
这是一个IP安全策略的 XML ,意思是每个用户只能在 ip为
------解决方案--------------------
悲剧啊悲剧啊。 domDocument是非常标准的DOM模型,php manual详细的方法和例子,为什么偷懒?
------解决方案--------------------PHP code
<?php $xml = <<<EOF<?xml version="1.0" encoding="utf-8"?><user><username name="admin"><iplist>192.168.1.1</iplist><iplist>192.168.1.2</iplist> <iplist>192.168.1.3</iplist> <iplist>192.168.1.4</iplist><iplist>192.168.1.5</iplist></username><username name="user"><iplist>192.168.1.11</iplist><iplist>192.168.1.12</iplist><iplist>192.168.1.13</iplist><iplist>192.168.1.14</iplist><iplist>192.168.1.15</iplist></username><username name="user2"><iplist>192.168.1.21</iplist><iplist>192.168.1.22</iplist><iplist>192.168.1.23</iplist><iplist>192.168.1.24</iplist><iplist>192.168.1.25</iplist></username></user>EOF;$dom = new DOMDocument();$ret = $dom->loadXML($xml, LIBXML_NOBLANKS);$xpath = new DOMXpath($dom);$node_list = $xpath->query('/user/username[@name="admin"]/iplist');for ($i = 0; $i != $node_list->length; ++ $i) { echo $node_list->item($i)->nodeValue . PHP_EOL;}?><br><font color="#e78608">------解决方案--------------------</font><br>
PHP code
$s =<user><username name="admin"><iplist>192.168.1.1</iplist><iplist>192.168.1.2</iplist><iplist>192.168.1.3</iplist><iplist>192.168.1.4</iplist><iplist>192.168.1.5</iplist></username><username name="user"><iplist>192.168.1.11</iplist><iplist>192.168.1.12</iplist><iplist>192.168.1.13</iplist><iplist>192.168.1.14</iplist><iplist>192.168.1.15</iplist></username><username name="user2"><iplist>192.168.1.21</iplist><iplist>192.168.1.22</iplist><iplist>192.168.1.23</iplist><iplist>192.168.1.24</iplist><iplist>192.168.1.25</iplist></username></user>XML;$dom = new domDocument;$dom->loadXML($s);$xpath = new DOMXPath($dom);//使用xpath定位修改$p = $xpath->query("//username[@name='admin']/iplist[.='192.168.1.1']")->item(0);$p->nodeValue = 'abcd';//使用xpath定位删除$p = $xpath->query("//username[@name='admin']/iplist[.='192.168.1.2']")->item(0);$p->parentNode->removeChild($p);echo $dom->saveXML();<div class="clear">
</div>