Search code examples
xmlpowershellnon-ascii-characters

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


I have an XML string like this one:

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

I would need to change it as follows, because I need to pass it as parameter to a REST web service, having a JSON body:

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

How can I do it by powershell?

Note that the string comes after reading the content of a file as:

$updatedSource = Get-Content $file -Raw

EDIT: to better clarify my requirement I would need to fill the JSON parameter like this:

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

EDIT: Adding target REST call. The code for the request is already correct, I tested it with a string populated as the target would be...

[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)


Solution

  • Finally resolved as follows:

    Replaced this code:

    $updatedSource = Get-Content $file -Raw

    with:

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

    The tabulations themselves are definitely not an issue since they are accepted as JSON value.