I have a sample XML file test.xml
that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Response>
<Update>
<foo>1.1.1</foo>
<bar>12345</bar>
</Update>
</Response>
I'm trying to use PowerShell to get the value of foo
. I can download and save the file into text.xml
and then access foo
. This works:
Invoke-RestMethod $myurl | Out-File test.xml
[xml]$abc = (Get-Content test.xml)
$abc.Response.Update.foo
However, I receive errors when I attempt to save the XML content into the $abc
variable like this:
[xml]$abc = (Invoke-RestMethod $myurl)
Error:
MetadataError: Cannot convert value "<?xml version="1.0" encoding="utf-8"?>
<Response>
<Update>
[...snip...]
</Update>
</Response>" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
What am I doing wrong here?
Update #1
This produces no output and no errors:
$abc = Invoke-RestMethod $myurl
$abc.Response
$abc.Response.Update
$abc.Response.Update.foo
Changing to Invoke-WebRequest
:
[xml]$abc = Invoke-WebRequest $myurl
Error is the same, but now there is three question marks in the beginning. So it's possible that the problem is somehow related to the file's encoding.
MetadataError: Cannot convert value "???<?xml version="1.0" encoding="utf-8"?>
<Response>
<Update>
[...snip...]
</Update>
</Response>" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
CodePudding user response:
Your symptom suggests that there are three unrecognized characters preceding the XML text returned by your web service.
- While three characters could generally indicate what constitutes a mis-decoded UTF-8 (pseudo) BOM,
- (a) such a BOM is usually only present in files on disk, not in web-service responses
- (b) even if it were mis-decoded as the default encoding used by the web cmdlets up to PowerShell 7.2.x, ISO-8859-1, it would print as

, not as???
Pragmatically speaking, assuming that the remaining text is properly decoded, you can simply skip the three characters as follows:
[xml] (Invoke-WebRequest $myUrl).Content.Substring(3)
If that doesn't help, use a text editor to examine the downloaded file and determine its de-facto encoding, then try to decode the raw bytes as a string with that encoding, as shown in this answer.
CodePudding user response:
Using Xml Linq :
using assembly System.Xml.Linq
$xml = @"
<?xml version="1.0" encoding="utf-8"?>
<Response>
<Update>
<foo>1.1.1</foo>
<bar>12345</bar>
</Update>
</Response>
"@
$doc = [System.Xml.Linq.XDocument]::Parse($xml)
$update = $doc.Descendants("Update").Foreach([System.Xml.Linq.XElement])
$foo = $update.Element("foo").Value
$bar = $update.Element("bar").Value
Write-Host "foo = " $foo "bar = " $bar