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."