Uncaught exception 'DOMException' with message 'Hierarchy Request Error'

I'm getting error while replacing or adding a child into a node.

Required is :

I want to change this to..

<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>John</person>
  <person>Thomas</person>
</contacts>

like this

<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <p>
      <person>Eva</person>
  </p>
  <person>John</person>
  <person>Thomas</person>
</contacts>

error is

Fatal error: Uncaught exception 'DOMException' with message 'Hierarchy Request Error'

my code is

function changeTagName($changeble) {
    for ($index = 0; $index < count($changeble); $index++) {
        $new = $xmlDoc->createElement("p");
        $new ->setAttribute("channel", "wp.com");
        $new ->appendChild($changeble[$index]);
        $old = $changeble[$index];
        $result = $old->parentNode->replaceChild($new , $old);
    }
}

Answers


The error Hierarchy Request Error with DOMDocument in PHP means that you are trying to move a node into itself. Compare this with the snake in the following picture:

Similar this is with your node. You move the node into itself. That means, the moment you want to replace the person with the paragraph, the person is already a children of the paragraph.

The appendChild() method effectively already moves the person out of the DOM tree, it is not part any longer:

$para = $doc->createElement("p");
$para->setAttribute('attr', 'value');
$para->appendChild($person);

<?xml version="1.0"?>
<contacts>
  <person>Adam</person>

  <person>John</person>
  <person>Thomas</person>
</contacts>

Eva is already gone. Its parentNode is the paragraph already.

So Instead you first want to replace and then append the child:

$para = $doc->createElement("p");
$para->setAttribute('attr', 'value');
$person = $person->parentNode->replaceChild($para, $person);
$para->appendChild($person);

<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <p attr="value"><person>Eva</person></p>
  <person>John</person>
  <person>Thomas</person>
</contacts>

Now everything is fine.


Need Your Help

setup software with visual studio 2012 and install shield 2010

deployment visual-studio-2012 installation installshield

I have developed an application with Visual Studio 2012. I have also created a setup.exe with Install Shield 2010 Premium for my application. My development environment is Windows 8 64-bit, the

read first 10MB from file using c#

c# md5 filestream

I need to get the first 10mb of a file and compute md5 from this, how can i achieve this? I cant find any sample of reading piece of a file.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.