【发布时间】:2011-01-23 18:10:58
【问题描述】:
对于列出元素名称和属性的递归函数的 SimpleXML 调用,我需要一些帮助。创建一个 XML 配置文件系统,但每个脚本都有自己的配置文件以及新的命名约定。所以我需要一种简单的方法来映射所有具有属性的元素,所以就像在示例 1 中一样,我需要一种简单的方法来调用所有进程,但我不知道如何在不对元素名称进行硬编码的情况下执行此操作函数调用。有没有办法递归调用函数来匹配子元素名称?我确实看到了 xpath 功能,但我没有看到如何将其用于属性。
示例中的 XML 看起来是否正确?我可以这样构造我的 XML 吗?
示例 1:
<application>
<processes>
<process id="123" name="run batch A" />
<process id="122" name="run batch B" />
<process id="129" name="run batch C" />
</processes>
<connections>
<databases>
<database usr="test" pss="test" hst="test" dbn="test" />
</databases>
<shells>
<ssh usr="test" pss="test" hst="test-2" />
<ssh usr="test" pss="test" hst="test-1" />
</shells>
</connections>
</application>
示例 2:
<config>
<queues>
<queue id="1" name="test" />
<queue id="2" name="production" />
<queue id="3" name="error" />
</queues>
</config>
伪代码:
// Would return matching process id
getProcess($process_id) {
return the process attributes as array that are in the XML
}
// Would return matching DBN (database name)
getDatabase($database_name) {
return the database attributes as array that are in the XML
}
// Would return matching SSH Host
getSSHHost($ssh_host) {
return the ssh attributes as array that are in the XML
}
// Would return matching SSH User
getSSHUser($ssh_user) {
return the ssh attributes as array that are in the XML
}
// Would return matching Queue
getQueue($queue_id) {
return the queue attributes as array that are in the XML
}
编辑:
我可以通过两个参数吗?关于你建议的第一种方法@Gordon
我刚收到,thnx,见下文
public function findProcessById($id, $name)
{
$attr = false;
$el = $this->xml->xpath("//process[@id='$id'][@name='$name']"); // How do I also filter by the name?
if($el && count($el) === 1) {
$attr = (array) $el[0]->attributes();
$attr = $attr['@attributes'];
}
return $attr;
}
【问题讨论】:
标签: php xml configuration recursion simplexml