通过 powershell 在 XML 字符串中用 \n 替换所有换行符并用 \t 替换制表符

Replace all line breaks with \n and tabulations with \t in a XML string by powershell

我有一个像这样的 XML 字符串:

<store:book name="history">
  <department>one</department>
  <department>two</department>
</store:book>

我需要按如下方式更改它,因为我需要将它作为参数传递给具有 JSON 正文的 REST Web 服务:

<store:book name="history">\n\t<department>one</department>\n\t<department>two</department>\n</store:book>

如何通过 powershell 完成?

请注意,字符串是在读取文件内容后出现的:

$updatedSource = Get-Content $file -Raw

编辑:为了更好地阐明我的要求,我需要像这样填写 JSON 参数:

$postData = "{""Source"":""${updatedSource}""}"

编辑:添加目标 REST 调用。请求的代码已经正确,我用填充的字符串测试了它,因为目标是...

[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest] [System.Net.WebRequest]::Create($finalUri)
$req.Headers.Add("Authorization", "Bearer " + $toolingService.SessionHeaderValue.sessionId)
$req.ContentType = "application/json"
$req.Method = "PATCH"

$postData = "{""Source"":""${updatedSource}""}"
$encodedContent = [System.Text.Encoding]::UTF8.GetBytes($postData)

$req.ContentLength = $encodedContent.length
$requestStream = $req.GetRequestStream()
$requestStream.Write($encodedContent, 0, $encodedContent.length)
$requestStream.Close()

[System.Net.WebResponse] $res =  $req.GetResponse()
[System.IO.StreamReader] $reader = New-Object System.IO.StreamReader($res.GetResponseStream(), [System.Text.Encoding]::UTF8)
$result = $reader.ReadToEnd()

$serializer = New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer
$obj = $serializer.DeserializeObject($result)

您可以使用替换功能:

$updatedSource = $updatedSource.Replace("`n","\n").Replace("`t","\t")

请注意,转义字符是反引号,而不是撇号。

最终解决如下:

替换了这段代码:

$updatedSource = Get-Content $file -Raw

与:

$updatedSource = Get-Content $file
$updatedSource = $updatedSource -join '\n'
$updatedSource = $updatedSource.replace("""","\""")

表格本身绝对不是问题,因为它们被接受为 JSON 值。