代码之家  ›  专栏  ›  技术社区  ›  Wilhelm Murdoch

使用DOMXPath替换节点,同时保持其位置不变

  •  0
  • Wilhelm Murdoch  · 技术社区  · 16 年前

    $Xml->load($source)
        ->path('//root/items')
        ->each(function($Context)
        {
            echo $Context->nodeValue;
        });
    

    $Xml->load($source)
        ->path('//root/items')
        ->walk('printValue', 'param1', 'param2');
    

    $Xml->load($source)
        ->path('//root/items')
        ->replace($Xml->createElement('foo', 'bar')); // can be an object, string or XPath pattern
    

    public function replace($Content)
    {
        foreach($this->results as $Element)
        {
            $Element->parentNode->appendChild($Content->cloneNode(true));
            $Element->parentNode->removeChild($Element);
        }
    
        return $this;
    }
    

    2 回复  |  直到 13 年前
        1
  •  2
  •   AnthonyWJones    16 年前

        2
  •  0
  •   Martijn Laarman    16 年前

    public function replace($Content)
    {
            foreach($this->results as $Element)
            {
                    if ($Element->nextSibling) {
                        $NextSiblingReference = $Element->nextSibling;
                        $Element->parentNode->insertBefore($Content->cloneNode(true),$NextSiblingReference);
                    }
                    else {
                        $Element->parentNode->appendChild($Content->cloneNode(true));   
                    }
                    $Element->parentNode->removeChild($Element);
            }
    
            return $this;
    }
    

    但完全未经测试。

    replaceChild 我怎么会错过那一刻:)