繁体   English   中英

将XML反序列化为WebAPI中的对象

[英]Deserialize xml to object from webapi

由于某些原因,我将不去讨论,因此无法将对象类型用作webapi控制器的参数。 因此,我需要找出一种使用XmlDocument或类似方法将xml对象反序列化为c#对象的方法。

这是我到目前为止的内容:

    public void Post(HttpRequestMessage request)
    {
        var xmlDoc = new XmlDocument();
        xmlDoc.Load(request.Content.ReadAsStreamAsync().Result);
        using (XmlReader xmlReader = new XmlNodeReader(xmlDoc))
        {
            Object obj = new XmlSerializer(typeof(myObject)).Deserialize(xmlReader);
            myObject scp = (myObject)obj;
        } 
    }

不幸的是,这引发了错误。 谁能提供一些关于如何将xml反序列化到对象中的建议?

tia

编辑:这是我要反序列化的xml:

<Student>
<studentid>1234</studentid>
<command>post</command>
<posttype>charge</posttype>
<transaction_description>This is a test post to the web api</transaction_description>
<payment_type>CC</payment_type>
<term_code>2013SPRING</term_code>
<amount>432.75</amount>
</Student>

这是我得到的错误:

System.InvalidOperationException:意外。 产生日期:2014年3月19日,星期三,格林尼治标准时间

System.InvalidOperationException:XML文档(1、2)中存在错误。 ---> System.InvalidOperationException:意外。 -在Microsoft.Xml.Serialization.GeneratedAssembly。
在System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)处
在C:\\ Projects \\ CashNetSSO \\ Development \\ CashNetSSO \\ CashNetSSO \\ Controllers \\ API \\ StudentInformationPostController.cs:第23行处的CashNetSSO.Controllers.API.StudentInformationPostController.Post(HttpRequestMessage请求)处:位于lambda_method(Closure,Object,Object [])的第23行System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(对象实例,Object []参数)上的System_Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor。<> c_ DisplayClassf.b _9(对象实例,Object [] methodParameters) )在System.Web.Http.Controllers.ReflectedHttpActionDescriptor。<> c_ DisplayClass5.b _4()在System.Threading.Tasks.TaskHelpers.RunSynchronously [TResult](Func`1 func,CancellationToken cancelledToken)

如果您已经以流形式读取内容,则可以执行以下操作:

    myObject scp = null;
    XmlSerializer serializer = new XmlSerializer(typeof(myObject);
    using (Stream stream = request.Content.ReadAsStreamAsync().Result)
    {
        scp = serializer.Deserialize(stream);
    }

编辑:

您收到错误的原因是因为XmlSerializer需要xml声明标签。 如果您的xml不包含此属性,则可以如下定义root属性:

    XmlSerializer serializer = new XmlSerializer(typeof(myObject), new XmlRootAttribute("Student"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM