在PHP中使用DOMDocument编辑XML元素的新属性

时间:2016-03-23 11:37:32

标签: php xml domdocument

我目前在我的MVC应用程序中有这个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>

我想使用DOMDocument为元素添加额外的“visibility = hidden”属性。怎么办呢?

2 个答案:

答案 0 :(得分:1)

使用createAttribute(),例如:

$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

输出

<?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>

答案 1 :(得分:0)

大多数人都使用DOMElement::setAttribute()DOMElement::setAttributeNS()方法。

$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();

输出:

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

然而,属性也是节点。因此,您可以使用DOMDocument::createAttribute()创建它们并使用DOMElement::setAttributeNode()进行设置。这允许将创建与赋值分开。

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