Chr*_*son 1 c# xmldocument xmlreader deserialization
由于某些原因,我将不去讨论,因此无法将对象类型用作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;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这引发了错误。谁能提供一些关于如何将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>
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
System.InvalidOperationException:意外。产生日期:2014年3月19日,星期三,格林尼治标准时间
System.InvalidOperationException:XML文档(1、2)中存在错误。---> System.InvalidOperationException:意外。-在Microsoft.Xml.Serialization.GeneratedAssembly 。 .API.StudentInformationPostController.Post(HttpRequestMessage请求)位于System.Web上lambda_method(Closure,Object,Object [])的C:\ Projects \ CashNetSSO \ Development \ CashNetSSO \ CashNetSSO \ Controllers \ API \ StudentInformationPostController.cs:第23行。 Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor。<> c_ DisplayClassf.b
。 .Serialization.XmlSerializer.Deserialize(Stream stream)
_9(Object实例,对象[] methodParameters)在System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object实例,对象[]参数)在System.Web.Http.Controllers.ReflectedHttpActionDescriptor。<> C_ DisplayClass5.b _4()在System.Threading.Tasks.TaskHelpers.RunSynchronously [TResult](Func`1函数,CancellationToken cancelToken)
如果您已经以流形式读取内容,则可以执行以下操作:
myObject scp = null;
XmlSerializer serializer = new XmlSerializer(typeof(myObject);
using (Stream stream = request.Content.ReadAsStreamAsync().Result)
{
scp = serializer.Deserialize(stream);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您收到错误的原因是因为XmlSerializer需要xml声明标签。如果您的xml不包含此属性,则可以如下定义root属性:
XmlSerializer serializer = new XmlSerializer(typeof(myObject), new XmlRootAttribute("Student"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7176 次 |
| 最近记录: |