强类型扩展示例

StronglyTypedExtensions 示例SyndicationFeed类用于示例。 但是,此示例中演示的模式可用于支持扩展数据的所有联合类。

联合对象模型(SyndicationFeed和相关 SyndicationItem类)支持使用 AttributeExtensionsElementExtensions 属性对扩展数据的松散类型访问。 此示例演示了如何通过实现 SyndicationFeedSyndicationItem 的自定义派生类,提供对扩展数据的强类型访问,使某些特定于应用程序的扩展作为强类型属性可用。

例如,此示例演示如何实现在建议的 Atom 线程扩展 RFC 中定义的扩展元素。 这仅用于演示目的,此示例不打算完全实现建议的规范。

示例 XML

以下 XML 示例显示了具有附加 <in-reply-to> 扩展元素的 Atom 1.0 条目。

<entry>
    <id>tag:example.org,2005:1,2</id>
    <title type="text">Another response to the original</title>
    <summary type="text">
         This is a response to the original entry</summary>
    <updated>2006-03-01T12:12:13Z</updated>
    <link href="http://www.example.org/entries/1/2" />
    <in-reply-to p3:ref="tag:example.org,2005:1"
                 p3:href="http://www.example.org/entries/1"
                 p3:type="application/xhtml+xml"
                 xmlns:p3="http://contoso.org/syndication/thread/1.0"
                 xmlns="http://contoso.org/syndication/thread/1.0">
      <anotherElement xmlns="http://www.w3.org/2005/Atom">
                     Some more data</anotherElement>
      <aDifferentElement xmlns="http://www.w3.org/2005/Atom">
                     Even more data</aDifferentElement>
    </in-reply-to>
</entry>

<in-reply-to>元素指定三个必需属性(reftypehref),同时允许存在其他扩展属性和扩展元素。

对 in-Reply-To 元素建模

在此示例中,<in-reply-to> 元素被建模为实现 IXmlSerializable 的 CLR,这就可以与 DataContractSerializer 一起使用。 它还实现一些用于访问元素数据的方法和属性,如以下示例代码所示。

[XmlRoot(ElementName = "in-reply-to", Namespace = "http://contoso.org/syndication/thread/1.0")]
public class InReplyToElement : IXmlSerializable
{
    internal const string ElementName = "in-reply-to";
    internal const string NsUri =
                  "http://contoso.org/syndication/thread/1.0";
    private Dictionary<XmlQualifiedName, string> extensionAttributes;
    private Collection<XElement> extensionElements;

    public InReplyToElement()
    {
        this.extensionElements = new Collection<XElement>();
        this.extensionAttributes = new Dictionary<XmlQualifiedName,
                                                          string>();
    }

    public Dictionary<XmlQualifiedName, string> AttributeExtensions
    {
        get { return this.extensionAttributes; }
    }

    public Collection<XElement> ElementExtensions
    {
        get { return this.extensionElements; }
    }

    public Uri Href
    { get; set; }

    public string MediaType
    { get; set; }

    public string Ref
    { get; set; }

    public Uri Source
    { get; set; }
}

InReplyToElement类实现了所需的属性(HRefMediaTypeSource),并为保存AttributeExtensionsElementExtensions提供了集合。

InReplyToElement 类实现 IXmlSerializable 接口,该接口允许直接控制对象实例读取和写入 XML 的方式。 该ReadXml方法首先读取从Ref传递过来的HRefSourceMediaTypeXmlReader属性的值。 任何未知属性都存储在集合中 AttributeExtensions 。 读取所有属性后, ReadStartElement() 将调用该读取器前进到下一个元素。 由于此类建模的元素没有必需的子元素,因此子元素会缓冲到 XElement 实例中并存储在集合中 ElementExtensions ,如以下代码所示。

public void ReadXml(System.Xml.XmlReader reader)
{
    bool isEmpty = reader.IsEmptyElement;

    if (reader.HasAttributes)
    {
        for (int i = 0; i < reader.AttributeCount; i++)
        {
            reader.MoveToNextAttribute();

            if (reader.NamespaceURI == "")
            {
                if (reader.LocalName == "ref")
                {
                    this.Ref = reader.Value;
                }
                else if (reader.LocalName == "href")
                {
                    this.Href = new Uri(reader.Value);
                }
                else if (reader.LocalName == "source")
                {
                    this.Source = new Uri(reader.Value);
                }
                else if (reader.LocalName == "type")
                {
                    this.MediaType = reader.Value;
                }
                else
                {
                    this.AttributeExtensions.Add(new
                                 XmlQualifiedName(reader.LocalName,
                                 reader.NamespaceURI),
                                 reader.Value);
                }
            }
        }
    }

    reader.ReadStartElement();

    if (!isEmpty)
    {
        while (reader.IsStartElement())
        {
            ElementExtensions.Add(
                  (XElement) XElement.ReadFrom(reader));
        }
        reader.ReadEndElement();
    }
}

WriteXml中,InReplyToElement方法首先将RefHRefSourceMediaType属性的值写出为XML属性。WriteXml不负责写出实际的外部元素,这是由调用WriteXml的方法来完成的。 它还将 AttributeExtensionsElementExtensions 的内容写入编写器,如下面的代码所示。

public void WriteXml(System.Xml.XmlWriter writer)
{
    if (this.Ref != null)
    {
        writer.WriteAttributeString("ref", InReplyToElement.NsUri,
                                            this.Ref);
    }
    if (this.Href != null)
    {
        writer.WriteAttributeString("href", InReplyToElement.NsUri,
                                                this.Href.ToString());
    }
    if (this.Source != null)
    {
        writer.WriteAttributeString("source", InReplyToElement.NsUri,
                                              this.Source.ToString());
    }
    if (this.MediaType != null)
    {
        writer.WriteAttributeString("type", InReplyToElement.NsUri,
                                                    this.MediaType);
    }

    foreach (KeyValuePair<XmlQualifiedName, string> kvp in
                                             this.AttributeExtensions)
    {
        writer.WriteAttributeString(kvp.Key.Name, kvp.Key.Namespace,
                                                   kvp.Value);
    }

    foreach (XElement element in this.ElementExtensions)
    {
        element.WriteTo(writer);
    }
}

ThreadedFeed 和 ThreadedItem

在示例中,SyndicationItemsInReplyTo 扩展由 ThreadedItem 类建模。 同样,ThreadedFeed类是SyndicationFeed类,其项都是ThreadedItem类的实例。

ThreadedFeed 继承自 SyndicationFeed,并重写 OnCreateItem 以返回一个 ThreadedItem。 它还实现了一种用于以Items方式访问ThreadedItems集合的方法,如以下代码所示。

public class ThreadedFeed : SyndicationFeed
{
    public ThreadedFeed()
    {
    }

    public IEnumerable<ThreadedItem> ThreadedItems
    {
        get
        {
            return this.Items.Cast<ThreadedItem>();
        }
    }

    protected override SyndicationItem CreateItem()
    {
        return new ThreadedItem();
    }
}

ThreadedItem 继承自 SyndicationItem,并将 InReplyToElement 设为强类型属性。 这样便可以方便地对 InReplyTo 扩展数据进行编程访问。 它还实现了TryParseElementWriteElementExtensions,用于读取和写入其扩展数据,如以下代码所示。

public class ThreadedItem : SyndicationItem
{
    private InReplyToElement inReplyTo;
    // Constructors
        public ThreadedItem()
        {
            inReplyTo = new InReplyToElement();
        }

        public ThreadedItem(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) : base(title, content, itemAlternateLink, id, lastUpdatedTime)
        {
            inReplyTo = new InReplyToElement();
        }

    public InReplyToElement InReplyTo
    {
        get { return this.inReplyTo; }
    }

    protected override bool TryParseElement(
                        System.Xml.XmlReader reader,
                        string version)
    {
        if (version == SyndicationVersions.Atom10 &&
            reader.NamespaceURI == InReplyToElement.NsUri &&
            reader.LocalName == InReplyToElement.ElementName)
        {
            this.inReplyTo = new InReplyToElement();

            this.InReplyTo.ReadXml(reader);

            return true;
        }
        else
        {
            return base.TryParseElement(reader, version);
        }
    }

    protected override void WriteElementExtensions(XmlWriter writer,
                                                 string version)
    {
        if (this.InReplyTo != null &&
                     version == SyndicationVersions.Atom10)
        {
            writer.WriteStartElement(InReplyToElement.ElementName,
                                           InReplyToElement.NsUri);
            this.InReplyTo.WriteXml(writer);
            writer.WriteEndElement();
        }

        base.WriteElementExtensions(writer, version);
    }
}

设置、生成和运行示例

  1. 确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。

  2. 若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。

  3. 若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。