Search code examples
powershelljson.net

Unable to convert XML to JSON using [newtonsoft.Json.JsonConvert]::SerializeXmlNode method in powershell


I am trying to convert the content of a xml file to json using powershell. When I call to the method, the powershell returns the error as below:

Method invocation failed because [Newtonsoft.Json.JsonConvert] does not contain a method named 'SerializeXmlNode'.
At line:1 char:1
+ $jsonText = [newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlDoc)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

I also checked the newtonsoft website below but the SerializeXmlNode method seemed to not have been deprecated: newtonsoft - SerializeXmlNode

Kindly check my script below:

Import-Module newtonsoft.json
$filename = "E:\Udemy\Complete Guide to XML For Microsoft Developers\Lecture 5\XMLClass_Downloads_2021_03_28\IntroSamples\Flight01.xml"
#[xml]$xmlDoc = [IO.File]::ReadAllText($filename) 
[xml]$xmlDoc = Get-Content $filename 

Write-Host $xmlDoc.OuterXml
Write-Host "------------------------------------------------------------"

$jsonText = [Newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlDoc)

How can I convert the xml to json using SerializeXmlNode method or any of its equivalent ?

Kind regards, Ken


Solution

  • Download the latest Json dll from here and unzip it somewhere after you have right-clicked the zip file, selected 'Properties' and unblocked it. Suppose you have chosen path 'C:\Program Files\NewtonSoft' to store the unzipped folder, then put this at the top of your script:

    $jsonDllPath = 'C:\Program Files\NewtonSoft\Json130r1\Bin\net40\Newtonsoft.Json.dll'
    Add-Type -Path $jsonDllPath
    
    $filename = 'E:\Udemy\Complete Guide to XML For Microsoft Developers\Lecture 5\XMLClass_Downloads_2021_03_28\IntroSamples\Flight01.xml'
    # load the xml file. This way, you are ensured to get the file encoding correct
    $xmlDoc = [System.Xml.XmlDocument]::new()
    $xmlDoc.Load($filename)
    
    Write-Host $xmlDoc.OuterXml
    Write-Host "------------------------------------------------------------"
    
    # this should now work:
    $jsonText = [Newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlDoc)
    

    Depending on the XML, if it has an xml declaration line or not, you may want to use [Newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlDoc.DocumentElement)