C# – How to deserialize only part of an XML document in C#


Here's a fictitious example of the problem I'm trying to solve. If I'm working in C#, and have XML like this:

<?xml version="1.0" encoding="utf-8"?>
    <Company>Acme Sales</Company>
    ... and on... and on....

the XML inside SalesPerson can be very long, megabytes in size. I want to deserialize the tag, but not deserialize the SalesPerson XML element instead keeping it in raw form "for later on".

Essentially I would like to be able to use this as a Objects representation of the XML.

[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
    public Car[] Car { get; set; }

    public Stream SalesPerson { get; set; }

public class Car
    public string StockNumber{ get; set; }

    public string Make{ get; set; }

    public string Model{ get; set; }

where the SalesPerson property on the Cars object would contain a stream with the raw xml that is within the <SalesPerson> xml element after being run through an XmlSerializer.

Can this be done? Can I choose to only deserialize "part of" an xml document?


p.s. example xml stolen from How to Deserialize XML document

Best Answer

It might be a bit old thread, but i will post anyway. i had the same problem (needed to deserialize like 10kb of data from a file that had more than 1MB). In main object (which has a InnerObject that needs to be deserializer) i implemented a IXmlSerializable interface, then changed the ReadXml method.

We have xmlTextReader as input , the first line is to read till a XML tag:

reader.ReadToDescendant("InnerObjectTag"); //tag which matches the InnerObject

Then create XMLSerializer for a type of the object we want to deserialize and deserialize it

XmlSerializer   serializer = new XmlSerializer(typeof(InnerObject));

this.innerObject = serializer.Deserialize(reader.ReadSubtree()); //this gives serializer the part of XML that is for  the innerObject data

reader.close(); //now skip the rest 

this saved me a lot of time to deserialize and allows me to read just a part of XML (just some details that describe the file, which might help the user to decide if the file is what he wants to load).