C#Mvc Api Xml无法在Powershell中将字符串转换为Xml
.NET应用程序 我有一个MVC4.5应用程序,带有返回xml文档的Api控制器。它看起来像这样:C#Mvc Api Xml无法在Powershell中将字符串转换为Xml,c#,xml,asp.net-mvc,api,powershell,C#,Xml,Asp.net Mvc,Api,Powershell,.NET应用程序 我有一个MVC4.5应用程序,带有返回xml文档的Api控制器。它看起来像这样: namespace App.Controllers { public class GetDataController : ApiController { public IEnumerable<MyStruct> Get() { //code to build IEnumerable<MyStruct>
namespace App.Controllers
{
public class GetDataController : ApiController
{
public IEnumerable<MyStruct> Get()
{
//code to build IEnumerable<MyStruct> ReturnList goes here...
return ReturnList;
}
}
}
返回的字符串如下所示:
[{"Prop1":"Value1","Prop2":"Value2"},{"Prop1":"Value1", "Prop2":"Value2"}]
错误 但是,我在尝试通过将该字符串转换为xml时出错
$xmlDoc = [xml]$doc
错误内容如下:
Data at the root level is invalid. Line 1, position 1.
我试过使用:
(New-Object System.Net.WebClient).DownloadFile($xmlURL,'c:\temp\file.xml')
$xmlSchedule = [xml](Get-Content 'c:\temp\file.xml')
以及
$bomutf8=[system.text.Encoding]::UTF8.GetPreamble()
if(($a=(New-Object System.Net.WebClient).Downloadstring($xmlURL)).startsWith($bomutf8))
{
[xml]$a=$a.remove(0,$bomutf8.length)
}
问题
我怎样才能避免这个错误?理想情况下,我希望在服务器端修复此错误,以便最终用户不会遇到相同的问题。该字符串不是有效的XML。看起来更像JSON.AddGlobalConfiguration.Configuration.Formatters.XmlFormatter.UseDataContractSerializer=true;应用程序启动全局,强制MVC返回Xml而不是JSON。你说得对。是的。我真不敢相信我居然忘了。。。但当我在浏览器中查看它时,为什么它会显示为XML呢?听起来IE为你们做了很多好事。你可以使用
[xml]($doc | convertfromjson)
@TheIncorrigible1哈哈,尽管我现在觉得自己很笨,但我至少可以说我在调试时使用了Chrome。我要坚持用“我是个傻瓜”的借口。
$bomutf8=[system.text.Encoding]::UTF8.GetPreamble()
if(($a=(New-Object System.Net.WebClient).Downloadstring($xmlURL)).startsWith($bomutf8))
{
[xml]$a=$a.remove(0,$bomutf8.length)
}