Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

php - Copy DOMNodes from one DOMDocument to another

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

$def  = new DOMDocument( '1.0' );
$rdef = new DOMDocument( '1.0' );
$def->load( $path );
$rdef->loadXML( $info );
$r = $def->getElementsByTagName( 'repository' )->item( 0 );
$s = $rdef->getElementsByTagName( 'repository' )->item( 0 );
try {
    $r->appendChild( $s );
}
catch ( DOMException $e ) {
    SPConfig::debOut( get_class( $s ) );
    SPConfig::debOut( $e->getMessage() );
}

The result is:

DOMElement
Wrong Document Error

So it seems to me that $rdef->getElementsByTagName( 'repository' )->item( 0 ) returns DOMElement object but the definition says it should be DOMNode object.

Any idea what is wrong about it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...