Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
$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(...)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.