【问题标题】:How can I dynamically read a classes XmlTypeAttribute to get the Namespace?如何动态读取类 XmlTypeAttribute 以获取命名空间?
【发布时间】:2011-08-08 01:58:25
【问题描述】:

我需要从以下类中读取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");

【问题讨论】:

    标签: xml c#-4.0 xml-serialization


    【解决方案1】:

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

    用法如下:

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

    【讨论】:

    • 感谢佩里的工作,只需更改类的类型的类型
    • @Carlos - 方法语法已修复
    猜你喜欢
    • 2012-12-05
    • 1970-01-01
    • 2022-01-05
    • 2013-05-15
    • 2010-10-31
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多