无法在 powershell 中使用 [newtonsoft.Json.JsonConvert]::SerializeXmlNode 方法将 XML 转换为 JSON

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

我正在尝试使用 powershell 将 xml 文件的内容转换为 json。 当我调用该方法时,powershell returns 错误如下:

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

我还检查了下面的 newtonsoft 网站,但 SerializeXmlNode 方法似乎没有被弃用: newtonsoft - SerializeXmlNode

请检查下面我的脚本:

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)

如何使用 SerializeXmlNode 方法或其任何等效方法将 xml 转换为 json?

亲切的问候, 肯

here 下载最新的 Json dll 并在获得 right-clicked zip 文件后将其解压缩到某个地方,选择 'Properties' 并取消阻止。 假设您选择路径 'C:\Program Files\NewtonSoft' 来存储解压缩的文件夹,然后将其放在脚本的顶部:

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

取决于 XML,如果它有一个 xml 声明行,你可能想要使用 [Newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlDoc.DocumentElement)