如何用PowerShell将XML字符串换行替换为 、制表符替换为
用PowerShell格式化XML字符串的方法
嘿,这个需求处理起来很顺手,咱们直接借助.NET的XML处理能力就能搞定自动格式化,不用手动拼接换行和缩进,还能保证XML结构的正确性。
下面是具体的实现代码,你可以直接复用:
# 定义你的原始XML字符串(如果是从其他地方获取的,替换这里的赋值即可) $originalXml = '<store:book name="history"> <department>one</department> <department>two</department> </store:book>' # 将字符串加载为XML文档对象 $xmlDoc = [xml]$originalXml # 配置XML格式化规则:启用缩进、用制表符作为缩进字符,去掉默认的XML声明(和你的目标格式匹配) $xmlSettings = [System.Xml.XmlWriterSettings]@{ Indent = $true IndentChars = "`t" OmitXmlDeclaration = $true } # 在内存中生成格式化后的XML内容 $memoryStream = New-Object System.IO.MemoryStream $xmlWriter = [System.Xml.XmlWriter]::Create($memoryStream, $xmlSettings) $xmlDoc.WriteTo($xmlWriter) $xmlWriter.Flush() $memoryStream.Position = 0 # 将内存流中的内容转换为字符串 $formattedXml = (New-Object System.IO.StreamReader($memoryStream)).ReadToEnd() # 输出最终的格式化XML $formattedXml
运行这段代码后,你就能得到符合要求的格式化XML:
<store:book name="history">
one two
</store:book>
如果需要调整缩进样式(比如用两个空格代替制表符),只需要把IndentChars的值改成" "就行,非常灵活。另外,如果你的原始XML字符串来自文件、变量或者其他命令输出,直接替换$originalXml的赋值逻辑就好——比如从文件读取可以用$originalXml = Get-Content -Path "你的文件路径" -Raw。
内容的提问来源于stack exchange,提问作者Marco Z.
相关产品推荐
相关产品推荐

