Copy DOMNodes from one DOMDocument to another

前端 未结 1 1664
-上瘾入骨i
-上瘾入骨i 2020-12-20 05:59

I\'ve been trying to combine two XML documents like this:

$def  = new DOMDocument( \'1.0\' );
$rdef = new DOMDocument( \'1.0\' );
$def->load( $path );
$rd         


        
相关标签:
1条回答
  • 2020-12-20 06:38

    Nothing wrong about it. DOMNodeList can hold any DOMNode instances or subclasses thereof. DOMElement extends DOMNode, so technically a DOMElement is a DOMNode as well. Same for DOMAttr.

    EDIT: The problem is you trying to copy into the other DOMDocument. You have to importNode the node into the Document first, before appending it.

    EDIT2: Try this please:

    $r = $def->getElementsByTagName( 'repository' )->item( 0 );
    $s = $rdef->getElementsByTagName( 'repository' )->item( 0 );
    $i = $def->importNode( $s, TRUE );
    $r->appendChild( $i , TRUE );
    

    EDIT3: Full example

    $srcXML = <<< XML
    <repositories>
        <repository>
            <element>foo</element>
        </repository>
    </repositories>
    XML;
    
    $destXML = <<< XML
    <repositories>
        <repository>
            <element>bar</element>
        </repository>
    </repositories>
    XML;
    
    $srcDoc  = new DOMDocument;
    $destDoc = new DOMDocument;
    $destDoc->formatOutput = TRUE;
    $destDoc->preserveWhiteSpace = FALSE;
    
    $srcDoc->loadXML( $srcXML );
    $destDoc->loadXML( $destXML );
    
    $destNode = $destDoc->getElementsByTagName('repository')->item( 0 );
    $srcNode  = $srcDoc->getElementsByTagName('repository')->item( 0 );
    $import   = $destDoc->importNode($srcNode, TRUE);
    $destNode->parentNode->appendChild($import);
    echo $destDoc->saveXML();
    

    gives

    <?xml version="1.0"?>
    <repositories>
      <repository>
        <element>bar</element>
      </repository>
      <repository>
        <element>foo</element>
      </repository>
    </repositories>
    
    0 讨论(0)
提交回复
热议问题