我像这样创建一个XmlDocument:
$doc = New-Object xml
然后,在添加节点后,我将其保存:
$doc.Save($fileName)
问题在于它没有将XML声明添加到文档开头,导致文档格式不正确。换句话说,它只保存了一个片段。我该如何为其添加正确的XML声明?
我像这样创建一个XmlDocument:
$doc = New-Object xml
$doc.Save($fileName)
问题在于它没有将XML声明添加到文档开头,导致文档格式不正确。换句话说,它只保存了一个片段。我该如何为其添加正确的XML声明?
或者您可以使用XmlDocument上的CreateXmlDeclaration方法,例如:
$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")
您需要使用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>