Мне нужна помощь в вызовах 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
Я только что понял, спасибо, смотрите ниже
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;
}