【问题标题】:Preserving XML Formatting in XML Attributes in Powershell在 Powershell 的 XML 属性中保留 XML 格式
【发布时间】:2018-03-16 18:43:16
【问题描述】:

我只是在加载 xml 文件并将其保存到一个新文件中。这会修改属性的格式并在value="foo"/>value="foo" /> 之间添加一个额外的空格

我知道PreserveWhitespace 不支持格式化属性。

有什么办法可以避免这些空格/格式出现在 XML 行的末尾?

Powershell 脚本

$filePath = "C:\BeforeSave.xml"
[xml]$apptypexml = New-Object System.Xml.XmlDocument
$apptypexml.PreserveWhitespace = $true
[xml] $apptypexml = [xml] (Get-Content  $filePath)
$apptypexml.Save("C:\AfterSave.xml")

保存前的 XML 示例

<?xml version="1.0"?>
<ApplicationTypes>
<executable>
<Item type="registry" value="HKEY_LOCAL_MACHINE\"/> 
<Item type="string" value="\Sample.exe"/> 
</executable>
</ApplicationTypes>

保存后输出 XML

<?xml version="1.0"?>
<ApplicationTypes>
<executable>
<Item type="registry" value="HKEY_LOCAL_MACHINE\ "/> <!-- Powershell is giving spaces in the end of attributes -->
<Item type="string" value="\Sample.exe" /> <!-- Powershell is giving spaces in the end of attributes -->
</executable>
</ApplicationTypes>

【问题讨论】:

  • ...为什么你觉得有必要这样做?
  • 来自 PS 的 XML 是有效的 XML。如果使用该 XML 的应用程序不接受它,那么您还有其他问题!
  • @guiwhatsthat 您的链接末尾有一个杂散的],因此无法加载。
  • @JamesC。谢谢,已更正

标签: powershell


【解决方案1】:

Hacky 解决方案是简单的文本替换:

(Get-Content -Path "C:\AfterSave.xml") -replace '" />','"/>' -replace ' "/>','"/>' | Set-Content "C:\AfterSave.xml"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多