日期:2014-05-17  浏览次数:20614 次

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

<?xml version="1.0" encoding="utf-8"?>
<user>
<username name="admin">
<iplist>192.168.1.1</iplist>
<iplist>192.168.1.2</iplist> //举个例子 假设,我想修改或删除admin ip2的,其他的保持不变
<iplist>192.168.1.3</iplist> //因为节点名都相同, 我这里是不是要给 <iplist> 加id
<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>

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

------解决方案--------------------
PHP code
$s =<<< XML
<?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>
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("//userna