Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save well-formed XML from PowerShell

Tags:

powershell

xml

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?

like image 590
Tamás Szelei Avatar asked Jun 01 '11 15:06

Tamás Szelei


People also ask

How do I get the contents of a XML file in PowerShell?

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.

Can PowerShell parse XML?

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.


1 Answers

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")
like image 190
Keith Hill Avatar answered Oct 06 '22 07:10

Keith Hill