在保留空格的同时修改 xml [英] Modify xml while preserving whitespace
本文介绍了在保留空格的同时修改 xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试在保留空格的同时替换 XML 文件中的属性时遇到了几个问题.
I'm running into several problems trying to replace an attribute in an XML file while preserving whitespace.
$xml = [xml](get-content data.xml)
$xml.Path.To.Attribute = $value
set-content data.xml [String]$value
结果:删除了微不足道的空格(即换行符)
Result: Insigificant whitespace (namely newlines) are removed
$xml = new-object xml
$xml.PreserveWhitespace = true
$xml.PreserveWhitespace
结果:PreserveWhitespace
仍然是 false
$xml = get-content data.xml
$xml = [regex]::replace($xml, "pattern", "replacement")
set-content data.xml $xml
结果:[regex]::replace
弄乱了行尾
我在这里吃疯狂的药丸吗?
Am I taking crazy pills here?
推荐答案
问题都是相关的:Get-Content
返回文本文件的行,而不是文本本身.当转换回字符串时,这些行会完全合并.
The problems were all related: Get-Content
returns lines of the text file, not the text itself. When cast back to a string, the lines are combined outright.
最好的解决方案是使用:
The best solution was to use:
$xml = [xml]([System.IO.File]::ReadAllText("data.xml"))
这篇关于在保留空格的同时修改 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文