1

そのため、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 ファイルを更新しようとしているため、これは問題です。これにより、変更後に読み取れなくなります。ここで私が間違っていることを知っている人はいますか?

4

2 に答える 2

2

これは私にとってはうまくいくようです:

$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)
于 2013-10-29T22:55:57.737 に答える
0

別のオプションは、PowerShell Community ExtensionsFormat-Xmlのコマンドを使用することです。たとえば、次のように呼ばれます。

...
$xml.employee.person.name = "John Smith"
$xml | Format-Xml > $file2
于 2013-10-30T00:52:10.920 に答える