Skip to main content
 首页 » 编程设计

c#之将 xml 反序列化为来自 webapi 的对象

2024年02月01日29pander-it

由于我不会在这里详述的原因,我不能将对象类型用作我的 webapi Controller 的参数。因此,我需要找到一种使用 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 反序列化为对象提供一些建议?

蒂亚

编辑:这是我要反序列化的 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: was not expected. Generated: Wed, 19 Mar 2014 20:18:58 GMT

System.InvalidOperationException: There is an error in XML document (1, 2). ---> System.InvalidOperationException: was not expected. at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderStudentChargePost.Read3_StudentChargePost() --- End of inner exception stack trace --- at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at CashNetSSO.Controllers.API.StudentInformationPostController.Post(HttpRequestMessage request) in C:\Projects\CashNetSSO\Development\CashNetSSO\CashNetSSO\Controllers\API\StudentInformationPostController.cs:line 23 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c_DisplayClassf.b_9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c_DisplayClass5.b_4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)

请您参考如下方法:

如果您已经在阅读流式内容,您可以执行以下操作:

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

编辑:

您收到错误的原因是因为 XmlSerializer 需要一个 xml 声明标记。如果您的 xml 不包含它,您可以像下面这样定义根属性:

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