How to keep in session XML-based objects?

2019-07-23 22:38发布

问题:

I'm receiving data from web-services in XML and I'm using that data via objects, build upon received XML. So, sometimes I need to store such user-specific objects between requests in session. I know that XMLDocument couldn't be stored explicitly (state server)... so I'm making a terrible construction like:

private string _data;
public XmlDocument Data
{
    get
    {
        XmlDocument res = new XmlDocument();
        if (!string.IsNullOrEmpty(_data))
        {
            res.InnerXml = _data;
            return res;
        }
        return null;
    }
    set { _data = value.InnerXml; }
} 

So i'm implicitly storing xml... it useful for me during development, because I don't know exactly what properties I need from entire object - I can make simple experimental properties with xpath etc in a pinch...

so it's comfortable fo me, but it looks very inefficient to construct xmldocument from string each time I need to get some data from any property of that class. Is there any way around?) thanks.

回答1:

If you need to store data across requests, there's really no getting around serializing and de-serializing the data during each request - with one exception. If you use in-process sessions, it's possible to store any object you want, including XMLDocument objects or even (forgive me for even mentioning this) open file handles and database connections. I wouldn't recommend making your application dependent on in-process sessions though because it will eliminate the possibility of putting the application in a web farm if that ever becomes necessary.

I think your best option is to optimize your current strategy. Are you making sure that the XMLDocument is only reconstructed once during each request? Instead of constructing an XMLDocument, maybe it would be more efficient for you to use an XMLReader, depending on how the XML data is actually used.