Rename an XML node using PHP

后端 未结 2 1300
自闭症患者
自闭症患者 2020-12-21 19:28

I\'m trying to figure out how to rename a node in XML using PHP?

I Have come this far:

$dom = new DOMDocument( \'1.0\' );
$dom->preserveWhiteSpace         


        
2条回答
  •  既然无缘
    2020-12-21 19:54

    My solution, with extended test case:

    // Changes the name of element $element to $newName.
    function renameElement($element, $newName) {
      $newElement = $element->ownerDocument->createElement($newName);
      $parentElement = $element->parentNode;
      $parentElement->insertBefore($newElement, $element);
    
      $childNodes = $element->childNodes;
      while ($childNodes->length > 0) {
        $newElement->appendChild($childNodes->item(0));
      }
    
      $attributes = $element->attributes;
      while ($attributes->length > 0) {
        $attribute = $attributes->item(0);
        if (!is_null($attribute->namespaceURI)) {
          $newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
                                      'xmlns:'.$attribute->prefix,
                                      $attribute->namespaceURI);
        }
        $newElement->setAttributeNode($attribute);
      }
    
      $parentElement->removeChild($element);
    }
    
    function prettyPrint($d) {
      $d->formatOutput = true;
      echo '
    '.htmlspecialchars($d->saveXML()).'
    '; } $d = new DOMDocument( '1.0' ); $d->loadXML(' jmansa 1 1 '); $xpath = new DOMXPath($d); $elements = $xpath->query('/library/data'); if ($elements->length == 1) { $element = $elements->item(0); renameElement($element, 'invites'); } prettyPrint($d);

    By the way, I added this solution as a comment to the PHP documentation for DOMElement.

提交回复
热议问题