从PowerShell中保存格式良好的XML

时间:2011-06-01 15:58:37

标签: xml powershell

我创建了一个像这样的XmlDocument:

$doc = New-Object xml

然后,在用节点填充之后,我保存它:

$doc.Save($fileName)

问题是它没有将XML声明添加到文档的开头,导致文档格式错误。换句话说,它只保存一个片段。如何向其添加正确的XML声明?

2 个答案:

答案 0 :(得分:15)

或者您可以在CreateXmlDeclaration上使用XmlDocument方法,例如:

$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")

答案 1 :(得分:11)

您需要使用XmlTextWriter类来格式化输出。这是一个示例,尽管您可能希望根据您添加标题之外的任何特定需求进行演变:

$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()

稍后,通过调用ToString对象上的StringBuilder方法,您可以看到以下输出:

PS C:\> $sb.ToString()
<?xml version="1.0" encoding="utf-16"?>
<html>Value</html>
相关问题