Search code examples
c#xmlserializer

How to deserialize xml from the second node


I would like to deserialize part of xml, I tried this, but it does not work.

class Program
{
    static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(Test), new XmlRootAttribute("Test"));
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("<Root1><Root2><Test><Id>5</Id></Test></Root2></Root1>")))
        {
            var test = serializer.Deserialize(stream);
        }           
    }
}

public class Test
{
    public int Id;
}

How can I say to XmlSerializer to start serialization from <Test>?


Solution

  • Move to desired node with XmlReader.

    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("<Root1><Root2><Test><Id>5</Id></Test></Root2></Root1>")))
    using (var reader = XmlReader.Create(stream))
    {
        reader.ReadToFollowing("Test");
        var test = (Test)serializer.Deserialize(reader);
    }