Powershell:将 XML 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15410455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Powershell: Convert XML to String
提问by uprix
I am searching for a way to convert a XML-Object to string.
我正在寻找一种将 XML 对象转换为字符串的方法。
Is there a way like $xml.toString() in Powershell?
Powershell 中是否有类似 $xml.toString() 的方法?
回答by Stanley De Boer
You are probably looking for OuterXml.
您可能正在寻找OuterXml.
$xml.OuterXmlshould give you what you want.
$xml.OuterXml应该给你你想要的。
回答by mjolinor
How are you creating the XML object?
您如何创建 XML 对象?
Typically, if you want an XML string from an object, you'd use:
通常,如果您想要来自对象的 XML 字符串,您可以使用:
$object | ConvertTo-Xml -As String
回答by Antonio Turkovic
Try this:
尝试这个:
[string[]]$text = $doc.OuterXml #or use Get-Content to read an XML File
$data = New-Object System.Collections.ArrayList
[void] $data.Add($text -join "`n")
$tmpDoc = New-Object System.Xml.XmlDataDocument
$tmpDoc.LoadXml($data -join "`n")
$sw = New-Object System.IO.StringWriter
$writer = New-Object System.Xml.XmlTextWriter($sw)
$writer.Formatting = [System.Xml.Formatting]::Indented
$tmpDoc.WriteContentTo($writer)
$sw.ToString()
I used this script to write my generated XML into a TextBox in Windows Forms.
我使用此脚本将生成的 XML 写入 Windows 窗体中的 TextBox。

