简体   繁体   中英

Deserialize xml string to c# Objects

I have this XML returned from a Refit rest service (WorkflowMax API):

<Response api-method=\"Current\"><Status>OK</Status><Jobs><Job><ID>J000002</ID><Name>Callout</Name><Description></Description><Client><ID>20970938</ID><Name>Big Co</Name></Client><ClientOrderNumber></ClientOrderNumber><State>Planned</State><StartDate>2019-04-25T00:00:00</StartDate><DueDate>2019-06-01T00:00:00</DueDate><Contact><ID>12918947</ID><Name>A Smith</Name></Contact><InternalID>34476268</InternalID><Manager><ID>787929</ID><Name>T Smith</Name></Manager><Partner><ID>787929</ID><Name>T Smith</Name></Partner><Assigned><Staff><ID>787929</ID><Name>T Smith</Name></Staff></Assigned></Job><Job><ID>J000003</ID><Name>Call </Name><Description></Description><Client><ID>20982774</ID><Name>Test Group</Name></Client><ClientOrderNumber></ClientOrderNumber><State>Planned</State><StartDate>2019-04-25T00:00:00</StartDate><DueDate>2019-04-25T00:00:00</DueDate><Contact><ID>12924082</ID><Name>S Smith</Name></Contact><InternalID>34476286</InternalID><Partner><ID>787929</ID><Name>T Smith</Name></Partner><Assigned><Staff><ID>787929</ID><Name>T Smith</Name></Staff></Assigned></Job></Jobs></Response>

I wish to convert to multiple C# Job objects. Can someone please suggest a simple way?

Tried Using visual studio Paste Special 'Paste XML as Classes' and just pasting in a single 'job' part of the XML it produces quite a complex Class and then not sure how to deserialize into the class it then has prodcued

Use this handy website to generate simple classes which you can then later on use to serialize or deserialize XML to: https://xmltocsharp.azurewebsites.net/

I would make use of the built-in XML serializer class to serialize or deserialize your classes/XML: https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?view=netframework-4.8

Some sample code:

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(Job));
  return (Job)serializer.Deserialize(reader);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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