I create an XmlDocument like this:
$doc = New-Object xml
Then, after filling it with nodes, I save it:
$doc.Save($fileName)
The problem is that it does not add the XML declaration to the beginning of the document, resulting in malformed document. In other words, it only saves a fragment. How can I add a correct XML declaration to it?
One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.
Another way to use PowerShell to parse XML is to convert that XML to objects. The easiest way to do this is with the [xml] type accelerator. By prefixing the variable names with [xml] , PowerShell converts the original plain text XML into objects you can then work with.
Or you can use the CreateXmlDeclaration
method on XmlDocument
e.g.:
$doc = new-object xml
$decl = $doc.CreateXmlDeclaration("1.0", $null, $null)
$rootNode = $doc.CreateElement("root");
$doc.InsertBefore($decl, $doc.DocumentElement)
$doc.AppendChild($rootNode);
$doc.Save("C:\temp\test.xml")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With