0

如何在 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

4 回答 4

0

要获得addressPLCidJS您可以获取父级并在父级中查找元素:

$addressPLC = $id->parentNode->getElementsByTagName("addressPLC");
echo $addressPLC->nodeValue;
于 2013-01-09T13:38:33.403 回答
0

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

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

于 2013-01-09T13:40:11.967 回答
0

我认为一种更可取的方法是遍历<module>节点(而不是 idJS 节点)并从该点检索 idJS 和 addressPLC。

看起来没有一种简单的方法可以按名称获取节点的子元素,但是您可以添加这个方便的函数(从这里开始:PHP DOMElement::getElementsByTagName - 无论如何只获取直接匹配的子元素?):

/**
 * 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;
  }
}
于 2013-01-09T13:42:48.110 回答
0

你真的应该为此使用xpath:

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

完毕。它也适用于getElementsByTagName. 见在线演示

<?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])');
于 2013-01-09T22:21:15.343 回答