XML object in setAttribute / addAttribute

Ok, maybe I missed something simple. I searched for quite some time and no luck. I need to insert an object into an XML attribute. To do this, I need to be able to use ampersand (&) in combination with the setAttribute method for the DOM class (or addAttribute for the simpleXML class). When I try to use it, it eludes the ampersand, therefore &entity; becomes &entity; . Trying to manually exit the ampersand \&entity; just leads to \&entity; . Ampersand Output &entity; just doubles it &entity; . I understand why he does this, ampersands will break the XML if they are not associated with a valid object. The problem is that it is related to the entity, and I cannot understand how to use it.

I found createEntityReference and DOMEntityReference , but the documentation for these methods is bad and I'm not sure if this is what I need. It appears that these terms only display the same PHP documentation, but from different sites. I tried to search for this problem separately, but I just get results explaining what I already know and pointed out above. I tried both the DOM and SimpleXML, but both give the same results. Am I just exaggerating this, or is it really not supported?

+4
source share
1 answer

Frankly, for me it was a difficult question, because I myself did not think about it, although the answer is quite simple:

According to the Level 1 recommendation of the DOM, the Attr interface inherits the Node interface, that is, you can attach nodes to the attribute. And EntityReference allowed in Attr children.

In XML, where an attribute value can contain entity references, Attr node child nodes provide a view in which object references are not extended. These child nodes can be either Text nodes or EntityReference nodes. Because the attribute type may not be known, there are no tokenized attribute values.

Here is a working example in PHP:

 <?php // a valid XML should contain used entities declarations to be valid, // but DOM recs do not contain means to generate DTD; // in PHP you can use XMLWriter for the purpose though $dtd = <<<DTD <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root [ <!ENTITY my_entity "some content"> ]> <root/> DTD; $xml = new DOMDocument(); $xml->formatOutput = true; $xml->loadXML($dtd); $root = $xml->documentElement; $entity = $xml->createEntityReference( 'my_entity' ); $an_attr = $xml->createAttribute( 'attr' ); $an_attr->appendChild( $xml->createTextNode('prefix ') ); $an_attr->appendChild( $entity ); $an_attr->appendChild( $xml->createTextNode(' suffix') ); $root->setAttributeNode( $an_attr ); // clone the entity to use it more than once $root->appendChild( $entity->cloneNode() ); print $xml->saveXML(); ?> 

that leads to

 C:\>\php\5.3.8\php.exe entities.php <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root [ <!ENTITY my_entity "some content"> ]> <root attr="prefix &my_entity; suffix">&my_entity;</root> 
+2
source

Source: https://habr.com/ru/post/1382579/


All Articles