gpt4 book ai didi

PHP DOM : How to move element into default namespace?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:47 27 4
gpt4 key购买 nike

我尝试了什么,什么不起作用:

  • 输入:

    $d = new DOMDocument();
    $d->formatOutput = true;

    // Out of my control:
    $someEl = $d->createElementNS('http://example.com/a', 'a:some');

    // Under my control:
    $envelopeEl = $d->createElementNS('http://example.com/default',
    'envelope');
    $d->appendChild($envelopeEl);
    $envelopeEl->appendChild($someEl);

    echo $d->saveXML();

    $someEl->prefix = null;
    echo $d->saveXML();
  • 替换后输出无效的 XML:

    <?xml version="1.0"?>
    <envelope xmlns="http://example.com/default">
    <a:some xmlns:a="http://example.com/a"/>
    </envelope>
    <?xml version="1.0"?>
    <envelope xmlns="http://example.com/default">
    <:some xmlns:a="http://example.com/a" xmlns:="http://example.com/a"/>
    </envelope>

请注意 <a:some>可能有 child 。一种解决方案是创建一个新的 <some> , 并复制 <a:some> 中的所有 child 至 <some> .是这是要走的路吗?

最佳答案

这真是一个有趣的问题。我的第一个意图是克隆 <a:some>节点,删除 xmlns:a属性,删除 <a:some>并插入克隆 - <a> .但这是行不通的,因为 PHP 不允许删除 xmlns:a 属性,就像任何常规属性一样。

在与 PHP 的 DOM 方法苦苦挣扎之后,我开始用谷歌搜索这个问题。我找到了 this在 PHP 文档中对此发表评论。用户建议编写一个函数,在没有命名空间的情况下手动克隆节点:

<?php

/**
* This function is based on a comment to the PHP documentation.
* See: http://www.php.net/manual/de/domnode.clonenode.php#90559
*/
function cloneNode($node, $doc){
$unprefixedName = preg_replace('/.*:/', '', $node->nodeName);
$nd = $doc->createElement($unprefixedName);

foreach ($node->attributes as $value)
$nd->setAttribute($value->nodeName, $value->value);

if (!$node->childNodes)
return $nd;

foreach($node->childNodes as $child) {
if($child->nodeName == "#text")
$nd->appendChild($doc->createTextNode($child->nodeValue));
else
$nd->appendChild(cloneNode($child, $doc));
}

return $nd;
}

使用它会导致这样的代码:

$xml = '<?xml version="1.0"?>
<envelope xmlns="http://example.com/default">
<a:some xmlns:a="http://example.com/a"/>
</envelope>';

$doc = new DOMDocument();
$doc->loadXML($xml);

$elements = $doc->getElementsByTagNameNS('http://example.com/a', 'some');
$original = $elements->item(0);

$clone = cloneNode($original, $doc);
$doc->documentElement->replaceChild($clone, $original);

$doc->formatOutput = TRUE;
echo $doc->saveXML();

关于PHP DOM : How to move element into default namespace?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15028966/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com