I'm trying to manipulate a xml file from sharepoint document library with powershell. Unfortunately I cannot open it and cast it to xml. :( I have same file in the document library and locally on hard drive. When I open it from hard drive everything is fine. When I open it from Sharepoint Document Library the cast to xml fails because of an extra character in the beginning of the file. I binary compared the result from $splistitem.File.OpenBinary() and from get-content C:....\file.xml and its the same. The problem is with getting the string from bytes. I tried all available encodings, but nothing worked. Here is my code:
# Add SharePoint snapin if needed
if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin Microsoft.SharePoint.Powershell
}
...
$splistitem = ...
...
$encode = New-Object System.Text.UTF8Encoding
[xml]$xmlFromSharepoint = $encode.GetString($splistitem.File.OpenBinary()) #throws exception
[xml]$xmlFromFile = get-content C:\....\file.xml #works fine
$web.Dispose()
Write-Host "Press any key to close ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
The exception thrown is with message:
Cannot convert value "?<?xml version="1.0" encoding="utf-8"?>
..." to type "System.Xml.XmlDocument". Error: "Data at the
root level is invalid. Line 1, position 1."
At C:\aaa.ps1:14 char:24
+ [xml]$xmlFromSharepoint <<<< = $encode.GetString($splistitem.File.OpenBinary
())
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMet
adataException
+ FullyQualifiedErrorId : RuntimeException