Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "This document already has a 'DocumentElement' node."

Tags:

powershell

xml

I've been trying to make an XML document for my school assigment, that if not existant in a directory would be created, and if it exists, would be appended, a log type of file. However when trying to append a new node into the file, I get the error: "This document already has a 'DocumentElement' node."

This is were I try to import and append the node

if (Test-Path "$destination\log.xml" -PathType Leaf) {
    [xml]$xml = Get-Content("$destination\log.xml")
    $element = $xml.ImportNode($doc.LastChild, $true)
    $xml.AppendChild($element)
}

and this is where I form the nodes

[xml]$doc = New-Object System.Xml.XmlDocument #Sukuriam naują XML dokumentą
$root = $doc.CreateNode("element","Backups", $null)
$root.InnerText = (Get-Date).ToString()
foreach ($file in $failai) {
    $failasNode = $doc.CreateNode("element","Failas",$null)
    $pavadinimas = $doc.CreateElement("Saltinis") 
    $data = $doc.CreateElement("Data")
    $takas = $doc.CreateElement("Vieta")
    $busena = $doc.CreateElement("Busena")

    #some other stuff, that puts info in the elements

    $failasNode.AppendChild($pavadinimas)
    $failasNode.AppendChild($busena) 
    $failasNode.AppendChild($data) 
    $failasNode.AppendChild($takas) 
    $root.AppendChild($failasNode) 
}
$doc.AppendChild($root)

The line

$xml.AppendChild($element)

returns an error message:

This document already has a 'DocumentElement' node.

like image 925
Erikas Byštautas Avatar asked Sep 06 '25 03:09

Erikas Byštautas


1 Answers

$xml.AppendChild() would append the element directly under the document root, i.e. as the root node. If the document already has a root node that operation will naturally fail, because an XML document cannot have multiple root nodes.

<?xml version="1.0" encoding="utf-8"?>
<rootnode>
  <!-- stuff -->
</rootnode>
<newnode>foo</newnode>      <!-- ← invalid! -->

To fix the issue, select the node under which you want to append the imported node and call AppendChild() on that node:

$xml.SelectSingleNode('/path/to/node').AppendChild(...)

For appending the imported node directly under the document root node you simplify the above to this:

$xml.DocumentElement.AppendChild(...)
like image 114
Ansgar Wiechers Avatar answered Sep 07 '25 19:09

Ansgar Wiechers