©
本文档使用 PHP中文网手册 发布
(PHP 5, PHP 7)
DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
$namespaceURI
, string $qualifiedName
)This function creates a new instance of class DOMAttr. 此节点出现在文档中,除非是用诸如 DOMNode->appendChild() 等函数来将其插入。
namespaceURI
The URI of the namespace.
qualifiedName
The tag name and prefix of the attribute, as prefix:tagname.
The new DOMAttr or FALSE
if an error occurred.
DOM_INVALID_CHARACTER_ERR
Raised if qualifiedName
contains an invalid character.
DOM_NAMESPACE_ERR
Raised if qualifiedName
is a malformed qualified
name, or if qualifiedName
has a prefix and
namespaceURI
is NULL
.
[#1] _ michael [2010-06-01 07:35:20]
If a new namespace is introduced while creating and inserting an attribute, createAttributeNS() does not behave in the same way as createElementNS().
(1) Location: With createAttributeNS(), the new namespace is declared at the level of the document element. By contrast, createElementNS() declares the new namespace at the level of the affected element itself.
(2) Timing: With createAttributeNS(), the new namespace is declared in the document as soon as the attribute is created - the attribute does not actually have to be inserted. createElementNS() doesn't affect the document as long as the element is not inserted.
An example:
<?php
$source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root><tag></tag></root>
XML;
$doc = new DOMDocument( '1.0' );
$doc->loadXML( $source );
// (1) We just create a "namespace'd" attribute without appending it to any element.
$attr_ns = $doc->createAttributeNS( '{namespace_uri_here}', 'example:attr' );
print $doc->saveXML() . "\n";
// (2) Next, we give the attribute a value and insert it.
$attr_ns->value = 'value';
$doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $attr_ns );
print $doc->saveXML() . "\n";
$doc = new DOMDocument( '1.0' );
$doc->loadXML( $source );
// (1) We create a "namespace'd" element without inserting it into the document.
$elem_ns = $doc->createElementNS( '{namespace_uri_here}', 'example:newtag' );
print $doc->saveXML() . "\n";
// (2) Next, we insert the new element.
$doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $elem_ns );
print $doc->saveXML() . "\n";
?>