1

there is an xml of the form below, tell me how to deserialize it to get an object. using the YAXLib library

<catalog>
    <categories>
        <category id="1">category 1</category>
        <category id="59349641">category 2</category>
        <category id="303608809">category 3</category>
        <category id="303614009">category 4</category>
        <category id="303643009">category 5</category>
    </categories>
</catalog>

how to get object from this xml ml with attributes

I tried this class but nothing is parsed

public class Сatalog
    {    
        public List<Category> categories { get; set; }
    }

public class Category
    {

        [YAXSerializeAs("id")]
        public int Id { get; set; }

        [YAXElementFor("category")]
        public string category { get; set; }

        [YAXSerializeAs("parentId")]
        public int ParentId { get; set; }    
    }

tried like this

  public class Сatalog
    {    
        public List<string> categories { get; set; }
    }

so we get only the text category

axuno
  • 581
  • 4
  • 15
Evgeny
  • 11
  • 1

1 Answers1

0

For anyone stumbling across a similar problem:

Here is the code to de/serialize:

[Test]
public void Xml_To_Object_YAXLib()
{
    const string xml = @"<catalog>
  <categories>
    <category id=""1"">category 1</category>
    <category id=""59349641"">category 2</category>
    <category id=""303608809"">category 3</category>
    <category id=""303614009"">category 4</category>
    <category id=""303643009"">category 5</category>
  </categories>
</catalog>";
    var serializer = new YAXSerializer(typeof(Catalog),new SerializerOptions
    {
        ExceptionHandlingPolicies = YAXExceptionHandlingPolicies.ThrowWarningsAndErrors,
        ExceptionBehavior = YAXExceptionTypes.Error,
        SerializationOptions = YAXSerializationOptions.DontSerializeNullObjects
    });

    var deserialized = (Catalog) serializer.Deserialize(xml);
    var serialized = serializer.Serialize(deserialized);
    Assert.That(serialized, Is.EqualTo(xml));
    Assert.That(deserialized.Categories.Count, Is.EqualTo(5));
    Assert.That(deserialized.Categories[4].Id, Is.EqualTo(303643009));
}

And this is how to decorate classes with attributes to instruct the YAXSerializer:

[YAXSerializeAs("catalog")]
public class Catalog
{
    [YAXSerializeAs("categories")]
    public List<Category> Categories { get; set; }
}

and

[YAXSerializeAs("category")]
public class Category
{
    [YAXSerializeAs("id")]
    [YAXAttributeForClass]
    public int Id { get; set; }

    [YAXValueForClass]
    public string CategoryName { get; set; }

    /// <summary>
    /// Assuming, this should also become an attribute to Category
    /// (although DevOp's XML didn't contain it)
    /// </summary>
    [YAXSerializeAs("parentId")]
    [YAXAttributeForClass]
    [YAXErrorIfMissed(YAXExceptionTypes.Ignore)]
    public int? ParentId { get; set; } 
}
axuno
  • 581
  • 4
  • 15