如何在XML中找到具有相同级别的其他节点值的节点?

时间:2013-01-09 13:31:34

标签: php xml

如何在XML中找到同一级别中具有其他节点值的节点? XML:

<config>
  <module>
    <idJS >001</idJS>
    <addressPLC>41000</addressPLC>
  </module>
  <module>
    <idJS >002</idJS>
    <addressPLC>42000</addressPLC>
  </module> 
</config>

PHP:

<?php
$doc = new DOMDocument();
$doc->load( 'file.xml' );
$config = $doc->getElementsByTagName( "module" );

$ids = $doc->getElementsByTagName('idJS');
foreach ($ids as $id) {
  if ($id->nodeValue == '001') {
      echo $addressPLC;
  }
}
?>

如何使用“idJS”获取“addressPLC”的nodeValue?

4 个答案:

答案 0 :(得分:0)

要让addressPLC拥有idJS,您可以获取父级并在父级中找到元素:

$addressPLC = $id->parentNode->getElementsByTagName("addressPLC");
echo $addressPLC->nodeValue;

答案 1 :(得分:0)

PHP中没有直接的方法来检索给定节点的所有兄弟节点。您需要通过$node->parentNode选择父元素,然后从该父元素开始并使用您已知的方法(例如getElementsByTagName())选择所需的元素。

在php.net上的DOM文档中还有一个用户注释,它有一个实现来查找给定节点的任何兄弟:http://php.net/dom#60188

答案 2 :(得分:0)

我认为最好的方法是遍历<module>节点(而不是idJS节点)并从该点检索idJS和addressPLC。

看起来没有一种简单的方法可以按名称获取节点的子元素,但是你可以添加这个方便函数(从这里:PHP DOMElement::getElementsByTagName - Anyway to get just the immediate matching children?):

/**
 * Traverse an elements children and collect those nodes that
 * have the tagname specified in $tagName. Non-recursive
 *
 * @param DOMElement $element
 * @param string $tagName
 * @return array
 */
function getImmediateChildrenByTagName(DOMElement $element, $tagName)
{
    $result = array();
    foreach($element->childNodes as $child)
    {
        if($child instanceof DOMElement && $child->tagName == $tagName)
        {
            $result[] = $child;
        }
    }
    return $result;
}

然后你就有了:

foreach ($config as $module) {
  $idJS = getImmediateChildrenByTagName($module, "idJS")[0];
  if ($idJS->nodeValue == '001') {
      echo getImmediateChildrenByTagName($module, "addressPLC")[0]->nodeValue;
  }
}

答案 3 :(得分:0)

你真的应该使用xpath:

$xp = new DOMXpath($doc);
echo $xp->evaluate('string(//module[./idJS[. = "001"]]/addressPLC[1])');

完成。它也适用于getElementsByTagName。请参阅online Demo

<?php

$buffer = <<<BUFFER
<config>
  <module>
    <idJS >001</idJS>
    <addressPLC>41000</addressPLC>
  </module>
  <module>
    <idJS >002</idJS>
    <addressPLC>42000</addressPLC>
  </module> 
</config>
BUFFER;

$doc = new DOMDocument();
$doc->loadXML( $buffer );

$modules = $doc->getElementsByTagName( "module" );

var_dump($modules);

foreach ($modules as $module)
{
    $ids = $module->getElementsByTagName('idJS');
    var_dump($ids);

    foreach ($ids as $id) {
        var_dump($id->nodeValue);
        if ($id->nodeValue == '001') {
            # ...
        }
    }
}

$xp = new DOMXpath($doc);
echo $xp->evaluate('string(//module[./idJS[. = "001"]]/addressPLC[1])');