我有一个这样的类(class):
public static class MyFeedExtensions
{
private readonly static XNamespace _namespace = XNamespace.Get(@"http://mynamespace");
public static XElement MyElement(string value)
{
return new XElement(_namespace + "MyElement", value);
}
}
我正在使用它来生成带有自定义扩展的 Atom Feed:
var feed = new SyndicationFeed();
feed.ElementExtensions.Add(MyFeedExtensions.MyElement("Testing!"));
这工作正常,除了提要将我的命名空间添加到元素:
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">Hello World!</title>
<id>00000000-0000-0000-0000-000000000000</id>
<updated>2011-03-01T01:00:53Z</updated>
<MyElement xmlns="http://mynamespace">Testing!</MyElement>
</feed>
有没有办法用提要注册命名空间,以获得这样的输出?
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:my="http://mynamespace">
<title type="text">Hello World!</title>
<id>00000000-0000-0000-0000-000000000000</id>
<updated>2011-03-01T01:00:53Z</updated>
<my:MyElement>Testing!</my:MyElement>
</feed>
理想情况下,当我有 SyndicationItems 和 ElementExtensions 时,我希望这也能工作,因为提要应该知道所有不同的命名空间。
(编辑:这纯粹是为了减少 XML 的大小并使人类更容易阅读)
最佳答案
在 this question 中找到答案并对其进行了调整:
feed.AttributeExtensions.Add(
new XmlQualifiedName("my",XNamespace.Xmlns.ToString()),
MyFeedExtensions.Namespace.ToString());
基本上:注册
xmlns:my
带有提要的属性,即使将元素添加到 SyndicationItem
中,它也会自动在元素上选取命名空间。饲料内。朦胧,但整洁!
关于.net - 将命名空间添加到 SyndicationFeed 而不是单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5149426/