Create an empty XmlDocument object with some default parameters

@param int $docOptions
@return DOMDocument object
324989
public static function createXmlDocument($docOptions = 0)
    {
        $xmldoc = new DOMDocument(self::XML_VERSION, self::XML_ENCODING);
        $xmldoc->preserveWhiteSpace =
            ($docOptions & XMLUTIL_OPT_DONT_PRESERVE_WHITESPACE) != XMLUTIL_OPT_DONT_PRESERVE_WHITESPACE
        ;
        $xmldoc->formatOutput = false;
        if (($docOptions & XMLUTIL_OPT_FORMAT_OUTPUT) == XMLUTIL_OPT_FORMAT_OUTPUT) {
            $xmldoc->preserveWhiteSpace = false;
            $xmldoc->formatOutput = true;
        }
        XmlUtil::$xmlNsPrefix[spl_object_hash($xmldoc)] = array();
        return $xmldoc;
    }
903039
private function createDomDocument(array $context): \DOMDocument
    {
        $document = new \DOMDocument();

        // Set an attribute on the DOM document specifying, as part of the XML declaration,
        $xmlOptions = [
            // nicely formats output with indentation and extra space
            self::FORMAT_OUTPUT => 'formatOutput',
            // the version number of the document
            self::VERSION => 'xmlVersion',
            // the encoding of the document
            self::ENCODING => 'encoding',
            // whether the document is standalone
            self::STANDALONE => 'xmlStandalone',
        ];
        foreach ($xmlOptions as $xmlOption => $documentProperty) {
            if ($contextOption = $context[$xmlOption] ?? $this->defaultContext[$xmlOption] ?? false) {
                $document->$documentProperty = $contextOption;
            }
        }

        return $document;
    }
1287690
public function xmlToArray(\SimpleXMLElement $xml, $options = array())
    {
        $defaults = array(
            'namespaceSeparator' => ':', //you may want this to be something other than a colon
            'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
            'alwaysArray' => array('entry'),   //array of xml tag names which should always become arrays
            'autoArray' => true,        //only create arrays for tags which appear more than once
            'textContent' => '$',       //key used for the text content of elements
            'autoText' => false,         //skip textContent key if node has no attributes or child nodes
            'keySearch' => false,       //optional search and replace on tag and attribute names
            'keyReplace' => false,       //replace values for above search values (as passed to str_replace())
        );
        $options = array_merge($defaults, $options);
        $namespaces = $xml->getDocNamespaces();
        $namespaces[''] = null; //add base (empty) namespace

        //get attributes from all namespaces
        $attributesArray = array();
        foreach ($namespaces as $prefix => $namespace) {
            foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
                //replace characters in attribute name
                if ($options['keySearch']) {
                    $attributeName = str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
                }
                $attributeKey = $options['attributePrefix']
                        .($prefix ? $prefix.$options['namespaceSeparator'] : '')
                        .$attributeName;
                $attributesArray[$attributeKey] = (string) $attribute;
            }
        }

        //get child nodes from all namespaces
        $tagsArray = array();
        foreach ($namespaces as $prefix => $namespace) {
            foreach ($xml->children($namespace) as $childXml) {
                //recurse into child nodes
                $childArray = $this->xmlToArray($childXml, $options);
                list($childTagName, $childProperties) = each($childArray);

                //replace characters in tag name
                if ($options['keySearch']) {
                    $childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
                }
                //add namespace prefix, if any
                if ($prefix) {
                    $childTagName = $prefix.$options['namespaceSeparator'].$childTagName;
                }

                if (!isset($tagsArray[$childTagName])) {
                    //only entry with this key
                    //test if tags of this type should always be arrays, no matter the element count
                    $tagsArray[$childTagName] =
                            in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
                            ? array($childProperties) : $childProperties;
                } elseif (
                    is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
                    === range(0, count($tagsArray[$childTagName]) - 1)
                ) {
                    //key already exists and is integer indexed array
                    $tagsArray[$childTagName][] = $childProperties;
                } else {
                    //key exists so convert to integer indexed array with previous value in position 0
                    $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
                }
            }
        }

        //get text content of node
        $textContentArray = array();
        $plainText = trim((string) $xml);
        if ($plainText !== '') {
            $textContentArray[$options['textContent']] = $plainText;
        }

        //stick it all together
        $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
                ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;

        //return node as array
        return array(
            $xml->getName() => $propertiesArray,
        );
    }
25595
public function validateDocument(DOMDocument $xmlDocument): array
    {
        $errors = [];

        $xpath = new DOMXPath($xmlDocument);
        $xpath->registerNamespace('docbook', 'http://docbook.org/ns/docbook');

        foreach ($xpath->query('//docbook:eztemplate') as $tagElement) {
            $tagName = $tagElement->getAttribute('name');
            if (empty($tagName)) {
                $errors[] = 'Missing RichText Custom Tag name';
                continue;
            }

            if (!isset($this->customTagsConfiguration[$tagName])) {
                @trigger_error(
                    "Configuration for RichText Custom Tag '{$tagName}' not found. " .
                    'Custom Tags configuration is required since 7.1, its lack will result in validation error in 8.x',
                    E_USER_DEPRECATED
                );
                continue;
            }

            $nonEmptyAttributes = [];
            $tagAttributes = $this->customTagsConfiguration[$tagName]['attributes'];

            // iterate over all attributes defined in XML document to check if their names match configuration
            $configElements = $xpath->query('.//docbook:ezconfig/docbook:ezvalue', $tagElement);
            foreach ($configElements as $configElement) {
                $attributeName = $configElement->getAttribute('key');
                if (empty($attributeName)) {
                    $errors[] = "Missing attribute name for RichText Custom Tag '{$tagName}'";
                    continue;
                }
                if (!isset($tagAttributes[$attributeName])) {
                    $errors[] = "Unknown attribute '{$attributeName}' of RichText Custom Tag '{$tagName}'";
                }

                // collect information about non-empty attributes
                if (!empty($configElement->textContent)) {
                    $nonEmptyAttributes[] = $attributeName;
                }
            }

            // check if all required attributes are present
            foreach ($tagAttributes as $attributeName => $attributeSettings) {
                if (empty($attributeSettings['required'])) {
                    continue;
                }

                if (!in_array($attributeName, $nonEmptyAttributes)) {
                    $errors[] = "The attribute '{$attributeName}' of RichText Custom Tag '{$tagName}' cannot be empty";
                }
            }
        }

        return $errors;
    }
1161586
public function getXML(\DOMDocument $document)
    {
        $xml = $document->createElement(sprintf('%s:TransactionDetails', $this->namespace));

        $comments = $document->createElement('ns1:Comments');
        $comments->textContent = $this->comments;

        $xml->appendChild($comments);

        if (!empty($this->invoiceNumber)) {
            $invoiceNumber = $document->createElement('ns1:InvoiceNumber');
            $invoiceNumber->textContent = $this->invoiceNumber;

            $xml->appendChild($invoiceNumber);
        }

        return $xml;
    }
248735
protected function createDom($uri, $source = null, array $httpOptions = [])
    {
        return (($source !== null) && strlen(trim($source))) ?
            Dom::createFromString($source) : Dom::createFromUri($uri, $httpOptions);
    }
707234
public function convert(DOMDocument $document)
    {
        $xpath = new DOMXPath($document);
        $xpathExpression = '//ns:pre';
        $ns = $document->documentElement->namespaceURI;
        $xpath->registerNamespace('ns', $ns);
        $elements = $xpath->query($xpathExpression);

        foreach ($elements as $element) {
            $element->textContent = str_replace(']]>', ']]]]><![CDATA[>', $element->textContent);
        }

        return $document;
    }
934117
public function setDocumentType(\Core\Entity\DocumentType $documentType = null) {
        $this->documentType = $documentType;

        return $this;
    }
456536
public static function create(string $contents)
    {
        $contextInst = new ContextFactory();

        $context = function (string $namespace) use ($contents, $contextInst) {
            return $contextInst->createForNamespace($namespace, $contents);
        };

        $phpdocInst = DocBlockFactory::createInstance();

        $phpdoc = function (string $doc, Context $context) use ($phpdocInst) {
            return $phpdocInst->create($doc, $context);
        };

        return new self($context, $phpdoc);
    }
193073
public function create($rawDocument)
    {
        /** @var \Magento\Framework\Search\DocumentField[] $fields */

        $entityIdFieldName = $this->entityMetadata->getEntityId();

        $rawDocument[Document::ID] = $rawDocument[$entityIdFieldName];

        return $this->objectManager->create($this->instanceName, ['data' => $rawDocument]);
    }
428687
public function createLink(array $options)
    {
        $str = ' ';
        foreach ($options as $key => $value) {
            if (($str !== ' ')) {
                $str .= ' '.$key.'="'.$value.'"';
            } else {
                $str .= $key.'="'.$value.'"';
            }
        }

        $html = '<link' . $str;
        if ($this->doctype == self::DOCTYPE_XHTML1_0_FRAMESET ||
                $this->doctype == self::DOCTYPE_XHTML1_0_STRICT ||
                $this->doctype == self::DOCTYPE_XHTML1_0_TRANSITIONAL) {
            $html .= '/>';
        } else {
            $html .= '>';
        }

        return $html;
    }
1168606
public static function fromString(string $xml) : DOMDocument
    {
        if (trim($xml) === '') {
            throw InvalidArgumentException::invalidType('non-empty string', $xml);
        }

        $entityLoader = libxml_disable_entity_loader(true);
        $internalErrors = libxml_use_internal_errors(true);
        libxml_clear_errors();

        $domDocument = self::create();
        $options = LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NONET;
        if (defined('LIBXML_COMPACT')) {
            $options |= LIBXML_COMPACT;
        }

        $loaded = $domDocument->loadXML($xml, $options);

        libxml_use_internal_errors($internalErrors);
        libxml_disable_entity_loader($entityLoader);

        if (!$loaded) {
            $error = libxml_get_last_error();
            libxml_clear_errors();

            throw new UnparseableXmlException($error);
        }

        libxml_clear_errors();

        foreach ($domDocument->childNodes as $child) {
            if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
                throw new RuntimeException(
                    'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'
                );
            }
        }

        return $domDocument;
    }
31496
public function setDefaultOptions(array $defaultOptions)
    {
        $this->defaultOptions['TTL'] = isset($defaultOptions['TTL']) ? $defaultOptions['TTL'] : 2419200;
        $this->defaultOptions['urgency'] = isset($defaultOptions['urgency']) ? $defaultOptions['urgency'] : null;
        $this->defaultOptions['topic'] = isset($defaultOptions['topic']) ? $defaultOptions['topic'] : null;
        $this->defaultOptions['batchSize'] = isset($defaultOptions['batchSize']) ? $defaultOptions['batchSize'] : 1000;

        return $this;
    }
698606
public static function toDOMDocument($xml)
    {
        if ($xml instanceof \DOMDocument) {
            return $xml;
        }

        if ($xml instanceof \SimpleXMLElement) {
            $doc = new \DOMDocument();
            $doc->loadXML('' . $xml->asXML());

            return $doc;
        }

        if (is_string($xml)) {
            $doc = new \DOMDocument();

            if (is_file($xml)) {
                $doc->load($xml);

                return $doc;
            }

            $doc->loadXML($xml);

            return $doc;
        }

        $type = is_object($xml) ? get_class($xml) : gettype($xml);

        throw new \InvalidArgumentException("Cannot convert instance of '$type' to DOMDocument");
    }
974853
function docToXML()
    {
        $this->DomDoc = new DOMDocument( '1.0', 'utf-8' );
        $this->DomRootElement = $this->DomDoc->createElement( 'doc' );
        $this->DomDoc->appendChild( $this->DomRootElement );

        if ($this->DocBoost !== null && is_numeric( $this->DocBoost ) )
        {
            // This will force the '.' as decimal separator and not depend on the locale
            $docBoost = sprintf('%F',$this->DocBoost);
            $this->DomRootElement->setAttribute( 'boost', $docBoost );
        }

        foreach ($this->Doc as $name => $field) {
            foreach( $field['content'] as $value )
            {
                // $value should never be array. Log the value and the stack trace.
                if ( is_array( $value ) )
                {
                    $backtrace = debug_backtrace();
                    $dump = array( $backtrace[0], $backtrace[1] );
                    eZDebug::writeError( 'Tried to index array value: ' . $name . "\nValue: " . var_export( $value, 1 ) .
                                         "\nStack trace: " . var_export( $dump, 1 ) );
                    continue;
                }
                $fieldElement = $this->DomDoc->createElement( 'field' );
                $fieldElement->appendChild( $this->DomDoc->createTextNode( $value ) );
                $fieldElement->setAttribute( 'name', $name );

                if ( $field['boost'] !== null && is_numeric( $field['boost'] ) )
                {
                    $fieldElement->setAttribute( 'boost', $field['boost'] );
                }

                $this->DomRootElement->appendChild( $fieldElement );
            }
        }


        $rawXML = $this->DomDoc->saveXML( $this->DomRootElement );
        //make sure there are no control characters left that could currupt the XML string
        return preg_replace('@[\x00-\x08\x0B\x0C\x0E-\x1F]@', ' ', $rawXML);
    }
429993
public function setCollectionOptions(array $collectionOptions)
    {
        if ($this->nested) {
            throw new LogicException(
                sprintf(
                    'Collection options cannot be set for nested document class "%s".',
                    $this->documentClass
                )
            );
        }

        $this->collectionOptions = $collectionOptions;

        return $this;
    }
485714
public function toXML(DOMElement $parent = null) : DOMElement
    {
        if ($parent === null) {
            $doc = DOMDocumentFactory::create();
            $e = $doc->createElementNS(Constants::NS_MD, 'md:EntitiesDescriptor');
            $doc->appendChild($e);
        } else {
            $e = $parent->ownerDocument->createElementNS(Constants::NS_MD, 'md:EntitiesDescriptor');
            $parent->appendChild($e);
        }

        if ($this->ID !== null) {
            $e->setAttribute('ID', $this->ID);
        }

        if ($this->validUntil !== null) {
            $e->setAttribute('validUntil', gmdate('Y-m-d\TH:i:s\Z', $this->validUntil));
        }

        if ($this->cacheDuration !== null) {
            $e->setAttribute('cacheDuration', $this->cacheDuration);
        }

        if ($this->Name !== null) {
            $e->setAttribute('Name', $this->Name);
        }

        Extensions::addList($e, $this->Extensions);

        /** @var \SAML2\XML\md\EntityDescriptor|\SAML2\XML\md\EntitiesDescriptor $node */
        foreach ($this->children as $node) {
            $node->toXML($e);
        }

        $this->signElement($e, $e->firstChild);

        return $e;
    }