0

Say I have something like this

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

is it possible use the YAXLib to Deserialize it into something like this

public class Note 
{
  public string to {get; set;}
  public string from {get; set;}
  public string Info {get; set;}
}

public class Info 
{
   public string header {get; set;}
   public string body {get; set;}
}

Is there any setting that I can change the pathing to make it go into my C# classes that I setup?

chobo2
  • 83,322
  • 195
  • 530
  • 832
  • See https://stackoverflow.com/a/17315863/1188513 and https://stackoverflow.com/a/4203551/1188513 – Mathieu Guindon Dec 01 '22 at 21:50
  • Though that is interesting I am trying to figure out how to use the YAXLib to take that xml file and use it deserialization into the classes I written. – chobo2 Dec 01 '22 at 21:54
  • I notice your class `Note` has a `string Info`. What are you expecting that string to be? – AceGambit Dec 01 '22 at 23:58

1 Answers1

1

Assuming you meant for the classes to look like so:

public class Note
{
    public string to { get; set; }
    public string from { get; set; }
    public Info Info { get; set; }
}

public class Info
{
    public string heading { get; set; }
    public string body { get; set; }
}

It seems the absolute simplest way to get what you want would be to have two separate deserializers. One for Info and one for Note and then deserialize (skipping errors for missing element) and stitch the two objects together yourself, like so:

Note GetNoteFromXml(string xml)
{
    var noteSer = new YAXSerializer<Note>(new SerializerOptions
    {
        ExceptionHandlingPolicies = YAXExceptionHandlingPolicies.DoNotThrow
    });
    var infoSer = new YAXSerializer<Info>();

    var note = noteSer.Deserialize(xml);
    var info = infoSer.Deserialize(xml);
    note.Info = info;
    return note;
}
var xml = @"<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

var note = GetNoteFromXml(xml);
AceGambit
  • 423
  • 3
  • 11