2

Is there a way to re-write this code using an IXmlSerializable, or better yet, via custom attributes?

// TODO:  how to harvest the namespaces from the request using a model and XmlSerializer?
var xmlStr = await Helper.Post (uri, request);
var xml = XDocument.Parse (xmlStr);
var node = (XElement) xml.FirstNode;
var ns = Namespaces = new XmlSerializerNamespaces ();

if (node.HasAttributes)
{
    foreach (var attr in node.Attributes ())
    {
        if (attr.IsNamespaceDeclaration)
        {
            ns.Add (attr.Name.LocalName, attr.Value);
        }
    }
}

I ask because I want to de-serialize the xml into a model and I want the model to contain all the namespaces declarations made in the response but I don't know what they are. This is an OGC GetCaps response an OGC uses namespaces to identify services, which are unknown at design-time.

Here's the same code in a fuller context:

    public async Task<Loader> Initialize (Uri uri)
    {
        var request = new GetCapabilities.GetCapabilitiesRequest ();
        // TODO: use another form of caching (or allow support for expiration)
        var response = Helper.CachedGetter.Post<GetCapabilities.GetCapabilitiesResponse> (uri, request);
        await response;
        GetCaps = response.Result;
        // TODO:  need to harvest the namespaces from the request but the model can't do it.
        {
            var xmlStr = await Helper.Post (uri, request);
            var xml = XDocument.Parse (xmlStr);
            var node = (XElement) xml.FirstNode;
            var ns = Namespaces = new XmlSerializerNamespaces ();

            if (node.HasAttributes)
            {
                foreach (var attr in node.Attributes ())
                {
                    if (attr.IsNamespaceDeclaration)
                    {
                        ns.Add (attr.Name.LocalName, attr.Value);
                    }
                }
            }
        }
        return this;
    }
Corey Alix
  • 2,694
  • 2
  • 27
  • 38
  • 2
    You can use [`XmlNamespaceDeclarationsAttribute`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlnamespacedeclarationsattribute(v=vs.110).aspx) to capture the xml namespaces for a given node during deserialization. Is that what you want? – dbc Mar 01 '18 at 23:53
  • I believe so. I hadn't seen that. Looking now. – Corey Alix Mar 02 '18 at 02:46

0 Answers0