Save well-formed XML from PowerShell
I create an XmlDocument like this:
$doc = New-Object xml
Then, after filling it with nodes, I save it:
$doc.Save($fi开发者_开发百科leName)
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?
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")
You need to use the XmlTextWriter class to format the output. Here is a sample, though you may want to evolve it for any specific needs you have beyond adding the header:
$doc = [xml]"<html>Value</html>"
$sb = New-Object System.Text.StringBuilder
$sw = New-Object System.IO.StringWriter($sb)
$writer = New-Object System.Xml.XmlTextWriter($sw)
$writer.Formatting = [System.Xml.Formatting]::Indented
$doc.Save($writer)
$writer.Close()
$sw.Dispose()
Later, by calling the ToString method on the StringBuilder object, you can see the following output:
PS C:\> $sb.ToString()
<?xml version="1.0" encoding="utf-16"?>
<html>Value</html>
精彩评论