Gets the XML namespace from an attribute marked on the type's definition - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Gets the XML namespace from an attribute marked on the type's definition

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization;
using System;/*from   www.j  ava 2 s  . co  m*/

public class Main{
        /// <summary>
        /// Gets the namespace from an attribute marked on the type's definition
        /// </summary>
        /// <param name="type"></param>
        /// <returns>Namespace of type</returns>
        public static string GetNamespace(Type type)
        {
            Attribute[] attrs = (Attribute[])type.GetCustomAttributes(typeof(DataContractAttribute), true);
            if (attrs.Length > 0)
            {
                DataContractAttribute dcAttr = (DataContractAttribute)attrs[0];
                return dcAttr.Namespace;
            }
            attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlRootAttribute), true);
            if (attrs.Length > 0)
            {
                XmlRootAttribute xmlAttr = (XmlRootAttribute)attrs[0];
                return xmlAttr.Namespace;
            }
            attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlTypeAttribute), true);
            if (attrs.Length > 0)
            {
                XmlTypeAttribute xmlAttr = (XmlTypeAttribute)attrs[0];
                return xmlAttr.Namespace;
            }
            attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlElementAttribute), true);
            if (attrs.Length > 0)
            {
                XmlElementAttribute xmlAttr = (XmlElementAttribute)attrs[0];
                return xmlAttr.Namespace;
            }
            return null;
        }
}

Related Tutorials