我有一个像这样的XML字符串:
<store:book name="history">
<department>one</department>
<department>two</department>
</store:book>
我需要按如下方式更改它,因为我需要将其作为参数传递给具有 JSON 正文的 REST Web 服务:
<store:book name="history">nt<department>one</department>nt<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)
您可以使用 Replace 函数:
$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 值。