[英]Powershell: Convert XML to String
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()的方式?
You are probably looking for OuterXml
.您可能正在寻找OuterXml
。
$xml.OuterXml
should give you what you want. $xml.OuterXml
应该给你你想要的。
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
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。
Since PowerShell 7+ , there is a very simple way to pretty-print XML using XElement
:自PowerShell 7+以来,有一种使用XElement
漂亮打印 XML 的非常简单的方法:
$xmlNode = [xml] '<foo x="42" y="21"><bar>baz</bar></foo>'
[System.Xml.Linq.XElement]::Parse( $xmlNode.OuterXml ).ToString()
Output: Output:
<foo x="42" y="21">
<bar>baz</bar>
</foo>
As the original poster of the C# answer wrote, it's not the most efficient way in terms of memory usage and execution time.正如C# 答案的原始发布者所写,就 memory 使用和执行时间而言,这不是最有效的方法。 Also you don't get much control over the formatting, eg I didn't find a way to print attributes on new lines.此外,您无法对格式进行太多控制,例如,我没有找到在新行上打印属性的方法。 If these things are important to you, the StringWriter
solution would be more appropriate.如果这些东西对你很重要,那么StringWriter
解决方案会更合适。
A simpler version:一个更简单的版本:
[string]$outputString = $XmlObject.childNode.childNode.theElementValueIWant.ToString()
Xml path is whatever your source XML tree structure is from the $XmlObject
. Xml 路径是来自$XmlObject
任何源 XML 树结构。
So if your $XmlObject
is:所以如果你的$XmlObject
是:
<xmlRoot>
<firstLevel>
<secondLevel>
<iWantThisValue>THE STRING I SEEK</iWantThisValue>
</secondLevel>
</firstLevel>
</xmlRoot>
you would use:你会使用:
[string]$outputString = $XmlObject.firstLevel.secondLevel.iWantThisValue.ToString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.