繁体   English   中英

如何使用自定义命名空间创建SyndicationFeed

[英]How to create a SyndicationFeed with a custom namespace

如何生成包含下图中显示的命名空间的Atom Feed? Atom提要的所有节点都必须以“a:”开头。

在此输入图像描述

这是我现在正在做的事情,但它不起作用。

    SyndicationFeed feed = new SyndicationFeed();
    XmlQualifiedName key = new XmlQualifiedName("os", "xmlns");
    feed.AttributeExtensions.Add(key, "http://a9.com/-/spec/opensearch/1.1/");

谢谢!

我相信它应该是

SyndicationFeed feed = new SyndicationFeed();
XmlQualifiedName key = new XmlQualifiedName("os", "http://www.w3.org/2000/xmlns/");
feed.AttributeExtensions.Add(key, "http://a9.com/-/spec/opensearch/1.1/");

更新:

在更仔细地阅读您的问题之后,我相信您可以通过覆盖Atom10FeedFormatter使用的XmlWriter实例的WriteStartElementWriteStartAttribute方法来实现此目的 您可以通过实现自定义XmlWriter类来完成此操作,如下例所示。

class AtomXmlTextWriter : XmlTextWriter
{
    private const string Atom10XmlNs = "http://www.w3.org/2005/Atom";
    private const string Atom10XmlNsPrefix = "a";

    public AtomXmlTextWriter(String filename, Encoding encoding)
        : base(filename, encoding)
    {
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement(GetAtomPrefix(ns), localName, ns);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        base.WriteStartAttribute(GetAtomPrefix(ns), localName, ns);
    }

    internal string GetAtomPrefix(string ns)
    {
        string prefix = string.Empty;

        if ((ns != null) && (ns.Equals(Atom10XmlNs)))
            prefix = Atom10XmlNsPrefix;

        return prefix;
    }
}

将自定义类与Atom10FeedFormatter一起使用

SyndicationFeed feed = new SyndicationFeed();
feed.AttributeExtensions.Add(new XmlQualifiedName("os", "http://www.w3.org/2000/xmlns/"), 
                             "http://a9.com/-/spec/opensearch/1.1/");

feed.AttributeExtensions.Add(new XmlQualifiedName(null, "http://www.w3.org/2000/xmlns/"),
                             http://schemas.zune.net/catalog/apps/2008/02");

using (XmlWriter writer = new AtomXmlTextWriter(@"TestFeed.xml", Encoding.UTF8))
{
    Atom10FeedFormatter feedFormatter = new Atom10FeedFormatter(feed);
    feedFormatter.WriteTo(writer);
}

产生所需的输出

<a:feed xmlns:os="http://a9.com/-/spec/opensearch/1.1/" 
        xmlns="http://schemas.zune.net/catalog/apps/2008/02" 
        xmlns:a="http://www.w3.org/2005/Atom">
    <a:title type="text" />
    <a:id>uuid:0f1b2c84-c935-459e-bc89-79d06b5a976b;id=1</a:id>
    <a:updated>2011-05-21T17:07:46Z</a:updated>
</a:feed>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM