【问题标题】:how do you add an attibute to root element of XML DOMDocument如何将属性添加到 XML DOMDocument 的根元素
【发布时间】:2015-08-14 08:08:00
【问题描述】:

我使用 DOMDocument 和 simpleXML 创建了一个 XML 文档。我需要为根元素添加一个属性。

以下是我创建文档和元素的方式。您会注意到,虽然文档最初是由 DOMDocument 创建的,但子/用户节点是使用简单的 XML 创建的。

$dom = new DOMDocument('1.0','UTF-8');

    /*** create the root element ***/ 
    $root = $dom->appendChild($dom->createElement( "Feed" )); 


    /*** create the simple xml element ***/ 
    $sxe = simplexml_import_dom( $dom ); 

    /*** add a user node ***/ 
    $firstChild = $sxe->addchild("FirstChild");  

我尝试像这样将属性添加到根目录:

$root = $dom->appendData($dom->createAttribute("extractDate", "$now"));

但这不起作用。

【问题讨论】:

  • 为什么要让DOMDocument::appendData()(甚至不存在的方法)起作用?你得到了哪个错误和返回值?您正在从您的问题中隐藏此重要信息。也许您只是遇到了错误?

标签: php xml domdocument


【解决方案1】:

使用DOMDocument,可以使用DOMElement::setAttribute方法设置属性:

$dom = new DOMDocument('1.0','UTF-8');
$root = $dom->createElement("Feed");  
$attr = $root->setAttribute("extractDate", "$now"); // <-- here

$dom->appendChild($root);

对于SimpleXML,您需要使用SimpleXMLElement::addAttribute 方法:

$sxe = simplexml_import_dom($dom);
$sxe->addAttribute("extractDate", "$now"); // <-- here

【讨论】:

  • 谢谢罗比。这是完美的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多