首页  >  文章  >  后端开发  >  请问一个XML有关问题

请问一个XML有关问题

WBOY
WBOY原创
2016-06-13 13:29:49810浏览

请教一个XML问题
这是一个IP安全策略的 XML ,意思是每个用户只能在 ip为 里面内容时才能登陆, 我想知道怎么修改 和删除某个用户的 ip列表, 我用的是 DOMDOCUMENT();




192.168.1.1
192.168.1.2 //举个例子 假设,我想修改或删除admin ip2的,其他的保持不变
192.168.1.3 //因为节点名都相同, 我这里是不是要给 加id
192.168.1.4
192.168.1.5


192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
192.168.1.15


192.168.1.21
192.168.1.22
192.168.1.23
192.168.1.24
192.168.1.25



------解决方案--------------------
悲剧啊悲剧啊。 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>

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn