Powershell Invoke-RestMethod将XML响应转换为JSON文本



我正在尝试使用Invoke-RestMethod命令从SOAP端点获取XML响应并将其转换为JSON文本。从我所读到的,Invoke-RestMethod应该为我将响应转换为自定义对象,所以这应该非常简单…这就是我正在尝试的....

$APIRequest = Invoke-RestMethod -Method Post -Uri $SOAPEndpointURL -Headers $requestHeader -Body $requestBody
$JSONResponse = ConvertTo-Json $APIRequest.Envelope -Depth 9

但这是我得到的结果JSON文本?

[ [ [ [ [ [ [ [] ], [], [ [] ], [], [ [] ], [ [] ], [ [] ], [ [] ], [ [] ], [ [] ], [ [] ], [ [] ], [ [] ], [], [], [ [] ], [ [] ], [ [] ], [ [] ], [], [ [] ], [ [] ], [ [] ], [ [] ], [], [ [] ], [ [] ], [ [] ], [ [] ] ] ], [ [] ], [] ] ] ] ]

谁能建议一个标准的方法来做到这一点,而不试图将XML响应手动解释为XML文本?

如果我更新我的请求来创建一个输出文件,那么我可以在文件中看到正确的XML响应。

$APIRequest = Invoke-RestMethod -Method Post -Uri $SOAPEndpointURL -Headers $requestHeader -Body $requestBody #-OutFile "C:SOAPResponse.txt"

如果我改变我的转换没有"-Depth "结果是这样的,这让人困惑吗?

[ [ [ "System.Xml.XmlElement" ] ] ]

为了提供更多的细节,下面是我使用PostMan调用端点时XML的样子。

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetCustomerListResponse>
<GetCustomerListResult>
<Data>
<Customer>
<AddressLine1>123 Yellow Street</AddressLine1>
<AddressLine2/>
<AddressPostCode>1234</AddressPostCode>
<AddressState/>
<AddressSuburb>Sydney</AddressSuburb>
<Email>test@test.com</Email>
<PgnRowNo>1</PgnRowNo>
</Customer>
</Data>
<Error>0</Error>
<ErrorMessage i:nil="true"/>
</GetCustomerListResult>
</GetCustomerListResponse>
</s:Body>
</s:Envelope>

PowerShell不提供XML到JSON的直接转换。

您需要处理API返回的XML,并将其转换为ConvertTo-Json可以处理的类型之一,如hashtable。

请看下面的例子:

# fetch XML
$xmlData = Invoke-RestMethod https://www.nasa.gov/rss/dyn/breaking_news.rss
# extract fields of interest
$hashtables = $xmlData | %{ @{ Id = $_.Identifier; Text = $_.InnerText } }
# convert hashtables into JSON
$hashtables | ConvertTo-Json

使用newtonsoft序列化器。
(根据您的系统/PowerShell版本newtonsoft可能已经可用,否则请参见:我如何使用Json。)

$Xml = [Xml]@"
<?xml version="1.0" encoding="utf-8"?>
<Book>
<projects>
<project name="Book1" date="2009-01-20">
<editions>
<edition language="English">En.Book1.com</edition>
<edition language="German">Ge.Book1.Com</edition>
<edition language="French">Fr.Book1.com</edition>
<edition language="Polish">Pl.Book1.com</edition>
</editions>
</project>
</projects>
</Book>
"@

[Newtonsoft.Json.JsonConvert]::SerializeXmlNode($Xml, 1)
{
"?xml": {
"@version": "1.0",
"@encoding": "utf-8"
},
"Book": {
"projects": {
"project": {
"@name": "Book1",
"@date": "2009-01-20",
"editions": {
"edition": [
{
"@language": "English",
"#text": "En.Book1.com"
},
{
"@language": "German",
"#text": "Ge.Book1.Com"
},
{
"@language": "French",
"#text": "Fr.Book1.com"
},
{
"@language": "Polish",
"#text": "Pl.Book1.com"
}
]
}
}
}
}
}