[英]C# how to deserialize a single nested class from xml
My C# class:我的 C# class:
[XmlRoot("ResultDetails")]
public class MyClass
{
[XmlElement("Id")]
public string Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
I'm receiving the XML from a SOAP request, so the soap body looks like this:我收到来自 SOAP 请求的 XML 请求,因此 soap 主体如下所示:
<soap:Body>
<Response xmlns="http://services.serviceprovider.co.uk/">
<Result>
<ResultDetails>
<Id>3636346</Id>
<Name>MyName</Name>
</ResultDetails>
</Result>
</Response>
</soap:Body>
And trying to deserialize it like this:并尝试像这样反序列化它:
var xmlResponse = XDocument.Load(soapResult);
var myClassRootElement = (from xElement in xmlResponse.Descendants()
where xElement.Name.LocalName == "ResultDetails"
select xElement).First();
var serializer = new XmlSerializer(typeof(MyClass));
var myClass= (MyClass)serializer.Deserialize(myClassRootElement.CreateReader());
The last line is throwing the following exception:最后一行抛出以下异常:
System.InvalidOperationException: There is an error in XML document (0, 0).
System.InvalidOperationException:XML 文档 (0, 0) 中存在错误。 ---> System.InvalidOperationException: <ResultDetails xmlns="http://services.serviceprovider.co.uk/"> was not expected.
---> System.InvalidOperationException: <ResultDetails xmlns="http://services.serviceprovider.co.uk/"> 不是预期的。
at Microsoft.Xml.Serialization.GeneratedAssembly在 Microsoft.Xml.Serialization.GeneratedAssembly
Which I don't understand why, because surely as I've set ResultDetails
as the XmlRoot
of MyClass
it should be exactly what the deserializer was expecting?我不明白为什么,因为我已经将
ResultDetails
设置为MyClass
的XmlRoot
它应该正是反序列化器所期望的?
Try following尝试关注
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApp2
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
Envelope envelope = (Envelope)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://www.w3.org/2003/05/soap-envelope/")]
public class Envelope
{
public Body Body { get; set; }
}
public class Body
{
public Response Response { get; set; }
}
public class Response
{
[XmlArray(ElementName = "Result")]
[XmlArrayItem("ResultDetails")]
public List<MyClass> MyClass { get; set; }
}
[XmlRoot("ResultDetails")]
public class MyClass
{
public string Id { get; set; }
public string Name { get; set; }
}
}
Used Xml二手 Xml
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/">
<soap:Body>
<Response xmlns="http://services.serviceprovider.co.uk/">
<Result>
<ResultDetails>
<Id>3636346</Id>
<Name>MyName</Name>
</ResultDetails>
</Result>
</Response>
</soap:Body>
</soap:Envelope>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.