如何动态读取类XmlTypeAttribute以获取命名空间?

时间:2011-04-18 17:44:16

标签: xml c#-4.0 xml-serialization

我需要阅读以下课程中的XmlTypeAttribute,以获取Namespace值:

<System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42"),  _
System.SerializableAttribute(),  _
System.Diagnostics.DebuggerStepThroughAttribute(),  _
System.ComponentModel.DesignerCategoryAttribute("code"),  _ 
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="http://webservices.micros.com/ows/5.1/Availability.wsdl")>  _
Partial Public Class AvailabilityRequest
Inherits AvailRequestSegmentList

Private summaryOnlyField As Boolean

Private xsnField As System.Xml.Serialization.XmlSerializerNamespaces

'''<comentarios/>
<System.Xml.Serialization.XmlAttributeAttribute()>  _
Public Property summaryOnly() As Boolean
    Get
        Return Me.summaryOnlyField
    End Get
    Set
        Me.summaryOnlyField = value
    End Set
End Property

使用以下代码,我可以获取System.SerializableAttribute的值,但是我无法检索有关XmlTypeAttribute的信息。

var ar = typeof (AvailabilityRequest).GetType();
ar.GetCustomAttributes(true);

更新2011.12.29

现在可以使用以下代码:

    var xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(
                          typeof(AvailabilityRequest),
                          typeof(XmlTypeAttribute)
                       );
   XNamespace ns = xmlAttribute.Namespace;
   ns.NamespaceName.Should().Be.EqualTo("http://webservices.micros.com/ows/5.1/Availability.wsdl");

1 个答案:

答案 0 :(得分:6)

Attribute类具有名为GetCustomAttribute的静态方法。

以下是用法:

XmlTypeAttribute xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(
                                   typeof(theType),
                                   typeof(XmlTypeAttribute)
                                 );
XNamespace ns = xmlAttribute.Namespace;