【问题标题】:Save XML adding space in blank fields保存 XML 在空白字段中添加空间
【发布时间】:2013-10-29 21:56:24
【问题描述】:

因此,我正在尝试学习如何使用 PowerShell 修改 XML 文件,但遇到了一个奇怪的问题,即 PowerShell 在保存 XML 文件后为其添加了空格。

假设我有一个名为 test.xml 的 xml 文件,它看起来像:

<employee>
    <person>
        <name>John Doe</name>
        <id></id>
    </person>
</employee>

我编写了这个 PowerShell 脚本来更改名称:

$file1 = ".\test.xml"
$file2 = ".\test_new.xml"
$xml = New-Object XML
$xml.Load($file1)
$xml.employee.person.name = "John Smith"
$xml.Save($file2)

到目前为止,一切都很好。但是,输出文件的格式如下:

<employee>
    <person>
        <name>John Smith</name>
        <id>
       </id>
    </person>
</employee>

这是一个问题,因为我正在尝试使用类似的代码来更新具有限制在空白字段中包含空格的架构的 XML 文件。这使得它在修改后不可读。 有谁知道我在这里做错了什么?

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    这似乎对我有用:

    $file1 = ".\test.xml"
    $file2 = ".\test_new.xml"
    
    # Remove old variable to ensure new instance
    Remove-Variable xml -ea SilentlyContinue
    
    # Create new empty xmldoc
    $xml = New-Object XML
    
    # Set preserve whitespace before load
    $xml.PreserveWhiteSpace = $true
    $xml.Load($file1)
    
    $xml.employee.person.name = "John Smith"
    
    #Set it again before save
    $xml.PreserveWhiteSpace = $true
    $xml.Save($file2)
    

    【讨论】:

    • 我收到此错误:Out-File : A parameter cannot be found that matches parameter name 'Path'. 如果我删除 -Path 参数,它可以工作,但输出文件不是 XML,只显示员工对象。
    • powershell 参数不一致的乐趣。
    • 看疯了PreserveWhiteSpace之后完全重写了
    • preservewhitespace 就是答案!
    【解决方案2】:

    另一种选择是使用来自PowerShell Community Extensions 的命令,称为Format-Xml,例如:

    ...
    $xml.employee.person.name = "John Smith"
    $xml | Format-Xml > $file2
    

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      相关资源
      最近更新 更多