views:

26

answers:

2

Hi guys,

.net, C#

Is it easily possible (by use of attributes etc) to automatically save the entire XML string (as a string field) that was created when an object was serialised when that object is deserialised?

I ask because I'm receiving an XML stub from a web service, and that stub contains a digital signature that I can use to verify the XML. I can deserialise the XML into a useful object that can be passed down into my application layer for verification, but I need the XML too. Ideally my new object would have an OriginalXML property or something. I could verify the XML at a higher level but it's not so convenient for me.

Cheers,

Chris.

A: 

You can load the XML file into a string, no problem. But the OriginalXML property would have to be marked with the [NonSerialized] attribute, because you don't want to store that string when you serialize. You'll have to deserialize, reload as an XmlDocument, and store the resulting string to that property.

XmlDocument xmlDoc = new XmlDocument();
try    {
    xmlDoc.Load(serializedFile);
}
catch (XmlException exc) {
    // Handle the error
}

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter= new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlWriter);

myObject.OriginalXML = xmlWriter.ToString();

HTH,
James

James B
Hi James, thanks for your response. It's pretty freaky really, because I have just written exactly the same code as you. I suppose I was hoping to not have to generate any custom deserialisation stuff as we have some pretty neatly encapsulated serialisation/deserialisation routines, but it's not a major problem. Thanks again!
Chris Chambers
Well, if we both came up with it, it must be the right answer! Feel free to mark it as such ;)
James B
Also, custom deserialization should not be necessary... just adding the `[NonSerialized]` attribute to the OriginalXML field should be enough to keep you out of serialization trouble.
James B
A: 

How about

[DataContract]
class FooBar
{
    //this property doesn't have the DataMember attribure 
    //and thus won't be serialized
    public string OriginalXml { get; set; }

    [DataMember] private int _foo;
    [DataMember] private string _bar;

    static public FooBar Deserialize(XmlReader reader)
    {
        var fooBar = 
           (FooBar)new DataContractSerializer(typeof(FooBar)).ReadObject(reader);
        fooBar.OriginalXml = reader.ToString();
        return fooBar;
    }        
}
ohadsc