Modify xml while preserving whitespace
I'm running into several problems trying to replace an attribute in an XML file while preserving whitespace.
Attempt 1
$xml = [xml](get-content data.xml)
$xml.Path.To.Attribute = $value
set-content data.xml [String]$value
Result: 开发者_如何学CInsigificant whitespace (namely newlines) are removed
Attempt 2
$xml = new-object xml
$xml.PreserveWhitespace = true
$xml.PreserveWhitespace
Result: PreserveWhitespace
remains false
Attempt 3
$xml = get-content data.xml
$xml = [regex]::replace($xml, "pattern", "replacement")
set-content data.xml $xml
Result: [regex]::replace
messes up the line endings
Am I taking crazy pills here?
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"))
This isn't working because PreserveWhiteSpace is a boolean:
$xml = new-object xml
$xml.PreserveWhitespace = true
$xml.PreserveWhitespace
Use:
xml.PreserveWhitespace = $true
By default empty lines are ignored, in order to preserve them you can change PreserveWhitespace
property before reading the file:
Create XmlDocument object and configure PreserveWhitespace:
$xmlDoc = [xml]::new()
$xmlDoc.PreserveWhitespace = $true
Load the document:
$xmlDoc.Load($myFilePath)
or
$xmlDoc.LoadXml($(Get-Content $myFilePath -Raw))
精彩评论