简体   繁体   中英

Use importNode other than the root or documentElement

Premise: The story is republished and any current tagnames should be preserved and any new tagnames should be added, creating a new story that has both original and new tagnames.

This all works... my issue is that if the republished story doesn't have a tags element at all, I need to create it and then import the tagnames from the original story.

$newXML='<story><metadata></metadata></story>';
$oldXML='<story><metadata><tags><tagname attribute="info"></tagname></tags></metadata></story>';

$newDom = new DomDocument;
$newDom->loadXML($newXML);

$newTagsNode = $newDom->createElement('tags','');

$oTags = $newDom->importNode($newTagsNode, true);
$newDom->documentElement->appendChild($oTags);

The issue is that I don't want oTags to live in 'documentElement' or 'root', I want them to live in story/metadata.

Is there a way to xpath/query/select 'metadata' and then append?

Use DOMXpath to find a list of elements by XPath. This will still return a node list, but you can provide more precision in your search. If at least one element is returned, make that the target node for the append operation.

$xpath = new DOMXpath($newDom);
$elemList = $xpath->query("/story/metadata");

if ($elemList->length > 0) {
    $elemList->item(0)->appendChild($oTags);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM