【问题标题】:PHP DOMElement is Immutable. = 'No Modification Allowed Error'PHP DOMElement 是不可变的。 = '不允许修改错误'
【发布时间】:2011-09-15 04:30:00
【问题描述】:

我不明白为什么会失败。 DOMElement 是否需要成为 Document 的一部分?

$domEl = new DOMElement("Item"); 
$domEl->setAttribute('Something','bla'); 

抛出异常

> Uncaught exception 'DOMException' with message 'No Modification Allowed Error';

我原以为我可以创建一个 DOMElement 并且它是可变的。

【问题讨论】:

  • 我发现 DOMElement 必须是某些 DOMDocument 的一部分才能正常工作。

标签: php xml dom


【解决方案1】:

来自http://php.net/manual/en/domelement.construct.php

创建一个新的 DOMElement 对象。 此对象是只读的。它可以附加到文档,但在节点与文档相关联之前,其他节点可能不会附加到该节点。要创建可写节点,请使用DOMDocument::createElement 或DOMDocument::createElementNS。

【讨论】:

  • 我知道它是旧的 thema,但有人愿意评论为什么它在 PHP 中这样做吗?
  • 我真的很想知道为什么。我试图使用 DOMElements 来测试制作要打印的标签(即我不想费心制作整个 DOMDocument)并遇到了这个错误。我真的很想知道这个“功能”背后的思考过程。
【解决方案2】:

我需要将 \DOMElement 的一个实例传递给一个函数以添加子元素,所以我最终得到了这样的代码:

class FooBar
{
    public function buildXml() : string
    {
        $doc = new \DOMDocument();
        $doc->formatOutput = true;

        $parentElement = $doc->createElement('parentElement');
        $this->appendFields($parentElement);

        $doc->appendChild($parentElement);

        return $doc->saveXML();
    }

    protected function appendFields(\DOMElement $parentElement) : void
    {
        // This will throw "No Modification Allowed Error"
        // $el = new \DOMElement('childElement');
        // $el->appendChild(new \DOMCDATASection('someValue'));

        // but these will work
        $el = $parentElement->appendChild(new \DOMElement('childElement1'));
        $el->appendChild(new \DOMCdataSection('someValue1'));

        $el2 = $parentElement->appendChild(new \DOMElement('childElement2'));
        $el2->setAttribute('foo', 'bar');
        $el2->appendChild(new \DOMCdataSection('someValue2'));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 2019-06-13
    • 1970-01-01
    • 2010-12-20
    • 2021-05-06
    • 2020-11-04
    • 2013-04-17
    • 2011-08-15
    相关资源
    最近更新 更多