1

I currently have this XML document in my MVC application

<elements>   
   <element name="agents" path="admin/agents" scope="system">
       <folder function="model">models</folder>
       <folder function="controller">controllers</folder>
       <folder function="view">views</folder>
   </element> 
</elements>

I would like to add additional "visibility=hidden" attribute to the element using DOMDocument. How can this be done?

2 Answers 2

1

Use createAttribute(), for example :

$raw = <<<XML
<elements>   
   <element name="agents" path="admin/agents" scope="system">
       <folder function="model">models</folder>
       <folder function="controller">controllers</folder>
       <folder function="view">views</folder>
   </element> 
</elements>
XML;
$doc = new DOMDocument();
$doc->loadXML($raw);

$visibility = $doc->createAttribute('visiblity');
$visibility->value = 'hidden';

$element = $doc->getElementsByTagName('element')->item(0);
$element->appendChild($visibility);
echo $doc->saveXML();

eval.in demo

output :

<?xml version="1.0"?>
<elements>   
   <element name="agents" path="admin/agents" scope="system" visiblity="hidden">
       <folder function="model">models</folder>
       <folder function="controller">controllers</folder>
       <folder function="view">views</folder>
   </element> 
</elements>
Sign up to request clarification or add additional context in comments.

Comments

0

Most people use the DOMElement::setAttribute() or DOMElement::setAttributeNS() method for this.

$xml = <<<XML
<elements>   
   <element name="agents" path="admin/agents" scope="system"> 
     ...
   </element> 
</elements>
XML;

$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('//element[1]') as $element) {
  $element->setAttribute('visibility', 'hidden');
}
echo $document->saveXML();

Output:

<?xml version="1.0"?>
<elements>   
   <element name="agents" path="admin/agents" scope="system" visibility="hidden"> 
     ...
   </element> 
</elements>

However attributes are nodes, too. So you can create them using DOMDocument::createAttribute() and set using DOMElement::setAttributeNode(). This allows to separate the creation from the assignment.

foreach ($xpath->evaluate('//element[1]') as $element) {
  $attribute = $document->createAttribute('visibility');
  $attribute->value = 'hidden';
  $element->setAttributeNode($attribute);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.